views:

183

answers:

2

What is the best way to have many children records pointing to one parent record in the same model/table in Django?

Is this implementation correct?:

class TABLE(models.Model):
    id = models.AutoField(primary_key=True)
    parent = models.ForeignKey("TABLE", unique=False)
+9  A: 

Django has a special syntax for ForeignKey for self-joins:

class TABLE(models.Model):
    id = models.AutoField(primary_key=True)
    parent = models.ForeignKey('self')

Source (second paragraph)

R. Bemrose
+2  A: 

Two things:

First, you need to allow the possibility of a null value for parent, otherwise your TABLE tree can have no root.

Second, you need to worry about the possibility of "I'm my own grandpa." For a lively discussion, see here.

David Berger