I'm quite familiar with Django, but recently noticed there exists a on_delete=models.CASCADE
and on_delete=models.PROTECT
options with the models,
on_delete=models.CASCADE
and on_delete=models.PROTECT
both are doing same things.Or both are same (I used the only on_delete=models.CASCADE
, when I remove the parent entry it will remove all related entries )
I have searched for the documentation for the same but couldn't find anything more than:
Django 2.0
A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete option. To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
When we set the on_delete parameter as CASCADE, deleting the reference object will also delete the referred object. This option is most useful in many relationships. Suppose a post has comments; when the Post is deleted, all the comments on that Post will automatically delete.
The PROTECT argument of the ForeignKey on_delete option prevents the referenced object from being deleted if it already has an object referencing it in the database. Put simply, Django will prevent a post from deletion if it already has comments.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.
CASCADE
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE
and also deletes the object containing the ForeignKey
.
PROTECT
Prevent deletion of the referenced object by raising
ProtectedError
, a subclass of django.db.IntegrityError
.
the things get deleted because once you change your model you need to do makemigrations
and migrate
to see the change.
For on_delete=models.CASCADE
:
You have 2 models i.e., Car and Company. You delete the company, you also delete the cars made by that company.
For on_delete=models.PROTECT
:
You have 2 models. Car and Company. You delete the company, Django says, Hold up. Can't do it ... So everything remains.
Here's what you'll see.
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