Home > OS >  Django ORM: ForeignKey=self and on_delete=PROTECT
Django ORM: ForeignKey=self and on_delete=PROTECT

Time:11-16

I have Model with next field:

some_field = ForeignKey('self', on_delete=PROTECT, blank=true, null=true, editable=false)

For what this field exist and what it does? Also I can`t delete obj of this model id adminpanel, cause it say "you can`t delete obj A, because would require deleting next protected obj: obj A"

Reason for this in this some_field?

CodePudding user response:

You can not delete this field/ object in the admin panel as it is a foreign key. And a data might be linked to it in another table. So in order to delete this object, you need to delete all the related objects available in the table where this foreign key is linked. You can read more about relations here

https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/

CodePudding user response:

If the object you are deleting is referenced through a foreign key relationship, Django prevents you from deleting it because you have set: on_delete=PROTECT.

If you want to allow deletion, you have to delete related objects as well. If you want that behavior:

from django.db.models import CASCADE

some_field = ForeignKey('self', on_delete=CASCADE, blank=true, null=true, editable=false)
  • Related