[英]Cannot delete some instances of model because of FK
Python 3.6 and Django 1.11.7.
Python 3.6 和 Django 1.11.7。
I've got two Models look like the following:我有两个模型如下所示:
class User():
name = models.CharField()
...
class UserInfo():
user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, related_name='info')
I wanted to delete some user instance A, and I explicitly deleted user A's info.我想删除一些用户实例 A,我明确删除了用户 A 的信息。 But when I tried to delete the user model
user.delete()
, I got the ProtecedError
:但是当我尝试删除用户 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>]>)
Then I tried to put the delete inside a try/catch looks like follows:然后我尝试将删除放在 try/catch 中,如下所示:
try:
user.delete()
except ProtectedError:
UserInfo.objects.filter(user=user).delete()
user.delete()
But still got the same exception.但仍然有同样的例外。 What might went wrong in my operation?
我的操作可能出了什么问题?
You are using a protect clause on the related objects:您正在相关对象上使用保护子句:
on_delete=models.PROTECT
You can check it in the documentation on:您可以在以下文档中查看它:
https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete
You have it pointed here:你在这里指出:
PROTECT[source] Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError. PROTECT [来源] 通过引发 django.db.IntegrityError 的子类 ProtectedError 来防止删除引用的 object。
Remove the on_delete=models.PROTECT
on your user
field.删除
user
字段上的on_delete=models.PROTECT
。 And run manage.py makemigrations
并运行
manage.py makemigrations
ForeignKey
fields have a default value of CASCADE
for the on_delete
argument.对于
on_delete
参数, ForeignKey
字段的默认值为CASCADE
。 This means that deleting the user object will cascade down and also delete the userinfo object linked to that user.这意味着删除用户 object 将级联并删除链接到该用户的用户信息 object。
Looks like this is the behaviour you are looking for.看起来这是您正在寻找的行为。
You can read more about this in the documentation documentation您可以在文档文档中阅读有关此内容的更多信息
Also note although on_delete
has a default value fo CASCADE
this argument will be required from Django 2.0.另请注意,尽管
on_delete
具有CASCADE
的默认值,但 Django 2.0 将需要此参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.