Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 541
Daniel Kivatinos Avatar asked Jan 21 '26 13:01

Daniel Kivatinos


2 Answers

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)

like image 71
Powerlord Avatar answered Jan 24 '26 02:01

Powerlord


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.

like image 45
David Berger Avatar answered Jan 24 '26 02:01

David Berger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!