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)
asked Apr 13, 2009 at 18:36
2
  • 3
    Unless 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. Commented Apr 13, 2009 at 18:43
  • 2
    Also, the default value of unique is False, so you don't need that Commented Apr 13, 2009 at 18:44

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.