[Solved]-Django model – on_delete=models.PROTECT()


Ignore your IDE. It is trying to get you to call the models.PROTECT function, which does indeed take those arguments. But you actually want to pass the function itself:

my_field = models.ForeignKey(..., on_delete=models.PROTECT)

ie without the parentheses that would call the function.

(Insert rant about using an IDE with a dynamic language here…)


Import like:(Python 2.7)

from django.db.models.deletion import PROTECT

Then you can use it directly.

category = ForeignKey(TCategory, PROTECT, null=False, blank=False)


models.PROTECT prevents deletions but does not raise an error by default.

you can create a custom exception for it, which is already protected.

from django.db import IntegrityError

class ModelIsProtectedError(IntegrityError):

def prevent_deletions(sender, instance, *args, **kwargs):
    raise ModelIsProtectedError("This model can not be deleted")

#in your models.py:
pre_delete.connect(prevent_deletions, sender=<your model>)

Leave a comment