S
S
Sergey Eremin2014-08-13 22:11:52
Django
Sergey Eremin, 2014-08-13 22:11:52

How to organize the parent-child relationship in models nicely in django?

Actually it would be desirable "beautiful" models for relations "the parent - child record" in one table. This is how it swears:

class Person (models.Model):
    FullName = models.CharField ( default=u"Иванов И.И.", max_length=256 )
    # ...
    Parent = models.OneToOneField ( Person )

    def __unicode__(self):
        return self.FullName

Most likely it will be possible to set the parent-child relationship manually, for example:
class Person (models.Model):
    id = models.IntegerField ( primary_key=True )
    FullName = models.CharField ( default=u"Иванов И.И.", max_length=256 )
    # ...
    Parent = models.IntegerField ( default=0, db_index=True )

    def __unicode__(self):
        return self.FullName

But I really want "pretty".
Actually, all this is necessary so as not to rewrite records in which there are many indexed fields. Rewriting indexes will slow down, and if you just add a new record and change the Parent of the old one, then this is a rebuild of only one index (Parent will also have to be indexed in order to quickly select records with Parent == 0)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
sim3x, 2014-08-13
@Sergei_Erjemin

You're running ahead of the locomotive
That's not necessary
, it's done by itself ORM
OneToOne is not about that. This is a field that links two models that, for some reason, have been separated. Previously, they were often used to link the hardcoded User and UserDetails model with additional fields that the
CamelCase developer needed - for
under_score classes - for variables, model fields, etc.

class Person(models.Model):
    full_name = models.CharField( default=u"Иванов И.И.", max_length=256 )
    # ...
    parent = models.ForeighKey('self', blank=True, null=True)
    # or
    # parent = models.ForeighKey("Person", blank=True, null=True)

But as before, you solve problems that don't exist yet.

R
Rrooom, 2014-08-13
@Rrooom

What about googling?
The relationship to self is established with the string "self".
Better yet, use django-mptt.

D
denizen, 2014-08-13
@denizen

try django-mptt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question