【发布时间】:2013-06-22 00:21:28
【问题描述】:
我正在尝试删除 Django 应用程序中的 User 对象,但在删除 User 时,我不断在相关对象中收到 IntegrityError。相关对象如下所示:
class Unfollowing(models.Model):
source = models.ForeignKey(User, related_name='unfollowings_by')
target = models.ForeignKey(User, related_name='unfollowings_of')
created_on = models.DateTimeField(auto_now_add=True)
但是在删除User 时,我收到如下错误:
IntegrityError:更新或删除表“auth_user”违反了表“core_unfollowing”上的外键约束“source_id_refs_id_5b69e09fc6161c2a”
详细信息:键 (id)=(6439) 仍从表“core_unfollowing”中引用。
有什么关系?删除关联的User 时,不应该自动删除相关的Unfollowing 对象吗?值得一提的是,我在Unfollowing.source 和Unfollowing.target 中都添加了一个明确的on_delete=models.CASCADE(尽管这是默认设置),但我仍然遇到同样的错误。
【问题讨论】:
-
您不是偶然使用代理模型(和较旧的 Django)吗? code.djangoproject.com/ticket/16128
-
@karthikr:
on_delete是模型字段的参数:docs.djangoproject.com/en/1.4/ref/models/fields/… -
@TimmyO'Mahony:不,不是代理模型。
-
另外(和推测)可能与
User模型有两个 FK 和on_delete不能同时关注related_names 有关系吗? -
@TimmyO'Mahony:我也是这么想的,但是通过
user.unfollowings_by.all().delete(); user.unfollowings_of.all().delete(); user.delete()明确删除相关模型导致了类似的错误。
标签: sql django django-models