[英]In Django, how to get all instances of a model where an instance of another model related to the first by fk does not exist?
[英]Cannot delete some instances of model because of FK
Python 3.6 和 Django 1.11.7。
我有两个模型如下所示:
class User():
name = models.CharField()
...
class UserInfo():
user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, related_name='info')
我想删除一些用户实例 A,我明确删除了用户 A 的信息。 但是当我尝试删除用户 model user.delete()
时,我得到了ProtecedError
:
ProtectedError: ("Cannot delete some instances of model 'User' because they are referenced through a protected foreign key: 'UserInfo.user'", <QuerySet [<UserInfo: UserInfo object>]>)
然后我尝试将删除放在 try/catch 中,如下所示:
try:
user.delete()
except ProtectedError:
UserInfo.objects.filter(user=user).delete()
user.delete()
但仍然有同样的例外。 我的操作可能出了什么问题?
您正在相关对象上使用保护子句:
on_delete=models.PROTECT
您可以在以下文档中查看它:
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete
你在这里指出:
PROTECT [来源] 通过引发 django.db.IntegrityError 的子类 ProtectedError 来防止删除引用的 object。
删除user
字段上的on_delete=models.PROTECT
。 并运行manage.py makemigrations
对于on_delete
参数, ForeignKey
字段的默认值为CASCADE
。 这意味着删除用户 object 将级联并删除链接到该用户的用户信息 object。
看起来这是您正在寻找的行为。
您可以在文档文档中阅读有关此内容的更多信息
另请注意,尽管on_delete
具有CASCADE
的默认值,但 Django 2.0 将需要此参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.