Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django self-referential foreign key

People also ask

Can a model have a foreign key of itself in Django?

To create a self-referential foreign key with Python Django, we can call ForeignKey with 'self' . to create the parent field in CategoryModel by setting it to models.

What is foreign key self in Django?

You can pass in the name of a model as a string to ForeignKey and it will do the right thing. So: parent = models.ForeignKey("CategoryModel") Or you can use the string "self" parent = models.ForeignKey("self")

What is self referencing foreign key?

A self-referencing constraint exists if a Db2® object is subject to a primary or foreign key relationship in which the parent table and the dependent table are the same table. If the DELETE rule for the relationship is CASCADE, the deletion or change of one row can cause a recursive deletion of other rows in the table.

Can a model have a foreign key to itself?

Self-referencing foreign keys are used to model nested relationships or recursive relationships. They work similar to how One to Many relationships. But as the name suggests, the model references itself. Self reference Foreignkey can be achived in two ways.


You can pass in the name of a model as a string to ForeignKey and it will do the right thing.

So:

parent = models.ForeignKey("CategoryModel")

Or you can use the string "self"

parent = models.ForeignKey("self")

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

class CategoryModel(models.Model):
    parent = models.ForeignKey('self')

https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey


You also to set null=True and blank=True

class CategoryModel(models.Model):
    parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)

null=True, to allow in database
blank=True, to allow in form validation


https://books.agiliq.com/projects/django-orm-cookbook/en/latest/self_fk.html

class Employee(models.Model):
    manager = models.ForeignKey('self', on_delete=models.CASCADE)

OR

class Employee(models.Model):
    manager = models.ForeignKey("app.Employee", on_delete=models.CASCADE)

https://stackabuse.com/recursive-model-relationships-in-django/