Good day. Please help with the following question.

It is necessary to describe the tree model in Django. The database used is Oracle.

I describe it this way:

class TelDivisions(models.Model): parent = models.ForeignKey('self') name = models.CharField(max_length=50, blank=True) class Meta: db_table = u'tel_divisions' 

but in this way parent refers to itself. How to make it refer to the id column of this table?

I thought it might turn out like this:

 class TelDivisions(models.Model): parent = models.ForeignKey(TelDivisions, db_column='id', blank=True) name = models.CharField(max_length=50, blank=True) class Meta: db_table = u'tel_divisions' 

but the python manage.py validate command revealed:

 parent = models.ForeignKey(TelDivisions, db_column='id', blank=True) NameError: name 'TelDivisions' is not defined 

What, in fact, is logical. How to be?

Thank.

    2 answers 2

    I recommend you to use django-mtpp . It was created just to display tree structures in the relational model.

    As for your question:

     parent = models.ForeignKey('self', db_column='id', blank=True) 

    And everything should work. You must refer to yourself through self. This example is described in django docs.

    One more thing. If you do not specify null = True, you will not be able to create a single root instance (that is, one that does not have a parent). Total:

     parent = models.ForeignKey('self', db_column='id', blank=True, null = True) 

    db_column = 'id' can be omitted, because it will, by default, refer to the key field of the table, i.e. id

      You do it correctly in the first variant, in the database there will be a parent_id column of integer type.

      Look at the article and comments, read, there are useful references, he himself recently dealt with this issue: trees in django-templates

      If the tree is multi-level, then mtpp is recommended for everyone, but if one level of nesting is like mine, then I managed without additional libraries.

      • Yes, it was the case, also stumbled upon this little article. Thank you) - adv-tsk