django model - on_delete=models.PROTECT()
I'm trying to u开发者_开发技巧se on_delete
with my models but my IDE is asking me for: collector, fields, sub_objs, using (i.e. ..., on_delete=models.PROTECT(collector, fields, sub_objs, using))
.
Can someone please tell me what these are and give me a quick example because I can find them documented anywhere :(
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):
pass
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>)
精彩评论