Daniel Kivatinos
Daniel Kivatinos

Reputation: 25046

Python/Django Modeling Question

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)

Upvotes: 2

Views: 301

Answers (2)

David Berger
David Berger

Reputation: 12823

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.

Upvotes: 2

Powerlord
Powerlord

Reputation: 88836

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)

Upvotes: 10

Related Questions