Skip to content Skip to sidebar Skip to footer

What Does On_delete=models.protect And On_delete=models.cascade Do On Django Models?

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_

Solution 1:

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

Solution 2:

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

Post a Comment for "What Does On_delete=models.protect And On_delete=models.cascade Do On Django Models?"