[Django]-What does on_delete=models.PROTECT and on_delete=models.CASCADE do on Django models?

63πŸ‘

βœ…

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

πŸ‘€Exprator

28πŸ‘

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

Leave a comment