【问题标题】:Integrity_Error (key is still referenced) thrown even with on_delete=do_nothing即使使用 on_delete=do_nothing 也会引发 Integrity_Error(仍引用密钥)
【发布时间】:2016-02-27 04:48:17
【问题描述】:

我有一个模型:

class Project(Model):
    name = models.TextField(...)
    ... bunch of fields ...

我还有一些模型可以在我的应用程序中跟踪历史记录。这些模型有ForeignKey 对Project 模型的引用:

class Historical_Milestone(Model):
    project = models.ForeignKey('Project', db_index=True, related_name='+',
                                on_delete=models.DO_NOTHING, blank=True, null=True)

当我删除 Project 表中的项目时,我收到以下 IntegrityError:

对表“project”的更新或删除违反了对表“historical_milestone”的外键约束 {...} 详细信息:键 (id)=(123) 仍从表“historical_milestone”中引用。

历史表中的列设置了related_name='+'(表示我不想要反向查找),我设置了on_delete=models.DO_NOTHING参数。根据the documentation on the DO_NOTHING option:

如果您的数据库后端强制执行引用完整性,这将导致 IntegrityError,除非您手动将 SQL ON DELETE 约束添加到数据库字段。

表示我不关心反向关系的related_name 标志不应该处理这个吗?我需要采取哪些手动步骤来修改 Historical_Milestone 表以防止发生此错误?

【问题讨论】:

    标签: django orm


    【解决方案1】:

    related_name 是为了方便起见,它不会影响 Django 创建的外键约束。设置related_name='+' 仅仅意味着你不想在ORM 中访问product.historical_milestone_set(或类似的)。

    如果你想在项目被删除后保留id,并且不强制执行外键约束,使用整数字段可能会更好。

    class Historical_Milestone(Model):
        project_id = models.PositiveIntegerField(db_index=True, blank=True, null=True)
    

    【讨论】:

    • 现在我怎么没想到呢?一个简单的修复。谢谢!
    猜你喜欢
    • 2022-01-08
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2016-03-22
    • 2013-08-04
    • 2014-04-30
    相关资源
    最近更新 更多