I'm trying to use 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))
.
我正在尝试使用on_delete和我的模型,但我的IDE要求我:collector,fields,sub_objs,using(即...,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 :(
有人可以请告诉我这些是什么,并给我一个快速的例子,因为我可以在任何地方找到它们:(
3 个解决方案
#1
15
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:
忽略你的IDE。它试图让你调用models.PROTECT函数,它确实采用了这些参数。但是你实际上想要传递函数本身:
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...)
(在这里插入关于使用带有动态语言的IDE的咆哮......)
#2
1
Import like:(Python 2.7)
导入如:(Python 2.7)
from django.db.models.deletion import PROTECT
Then you can use it directly.
然后你可以直接使用它。
category = ForeignKey(TCategory, PROTECT, null=False, blank=False)
#3
-1
models.PROTECT prevents deletions but does not raise an error by default.
models.PROTECT可以防止删除,但默认情况下不会引发错误。
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>)
#1
15
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:
忽略你的IDE。它试图让你调用models.PROTECT函数,它确实采用了这些参数。但是你实际上想要传递函数本身:
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...)
(在这里插入关于使用带有动态语言的IDE的咆哮......)
#2
1
Import like:(Python 2.7)
导入如:(Python 2.7)
from django.db.models.deletion import PROTECT
Then you can use it directly.
然后你可以直接使用它。
category = ForeignKey(TCategory, PROTECT, null=False, blank=False)
#3
-1
models.PROTECT prevents deletions but does not raise an error by default.
models.PROTECT可以防止删除,但默认情况下不会引发错误。
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>)