Categories
Python Answers

How to create a self-referential foreign key with Python Django?

Spread the love

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'.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *