20
votes

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

1

1 Answers

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