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)
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With