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)
asked Apr 13, 2009 at 18:36
Daniel Kivatinos
25.2k23 gold badges65 silver badges82 bronze badges
-
3Unless I'm missing something, you don't need the id field, that'll be generated for you automatically as an auto-incrementing primary key field.Dominic Rodger– Dominic Rodger2009年04月13日 18:43:57 +00:00Commented Apr 13, 2009 at 18:43
-
2Also, the default value of unique is False, so you don't need thatDominic Rodger– Dominic Rodger2009年04月13日 18:44:29 +00:00Commented Apr 13, 2009 at 18:44
2 Answers 2
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)
answered Apr 13, 2009 at 18:40
Powerlord
89.1k17 gold badges130 silver badges179 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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.
answered Apr 13, 2009 at 18:45
David Berger
12.9k6 gold badges42 silver badges53 bronze badges
Comments
lang-py