Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does on_delete=models.PROTECT and on_delete=models.CASCADE do on Django models?

Tags:

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

like image 369
Mr Singh Avatar asked May 24 '18 06:05

Mr Singh


People also ask

What does On_delete models Cascade do?

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.

What does Django DB models model ForeignKey On_delete protect do?

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.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

What does ForeignKey mean in Django?

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.


2 Answers

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

like image 179
Exprator Avatar answered Sep 21 '22 12:09

Exprator


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.enter image description here

like image 43
Mujeeb Ishaque Avatar answered Sep 22 '22 12:09

Mujeeb Ishaque