Sometimes, we want to create a self-referential foreign key with Python Django
In this article, we’ll look at how to create a self-referential foreign key with Python Django.
How to create a self-referential foreign key with Python Django?
To create a self-referential foreign key with Python Django, we can call ForeignKey
with 'self'
.
For instance, we write
class CategoryModel(models.Model):
parent = models.ForeignKey('self')
to create the parent
field in CategoryModel
by setting it to models.ForeignKey('self')
to create a self-referencing foreign key field parent
.
Conclusion
To create a self-referential foreign key with Python Django, we can call ForeignKey
with 'self'
.