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.
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")
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.
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 databaseblank=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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With