Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Models self reference [duplicate]

I need to build a Django Model in which it refers to itself (a list of the same Model type within each instance of this model, sort of like a nested structure), probably within its own definition.

I have looked into ManyToManyField or a possible solution with another model with a foreign key to this Model. What's the simplest way to do it ?


1 Answers

You can use the string 'self' to indicate a self-reference.

class Region(models.Model):
    country = models.ForeignKey('self')

more in django docs

like image 174
vanadium23 Avatar answered Jun 11 '26 17:06

vanadium23



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!