gpt4 book ai didi

django - Integrity_Error(键仍然被引用)即使在 on_delete=do_nothing 时也会抛出

转载 作者:行者123 更新时间:2023-12-05 05:24:45 26 4
gpt4 key购买 nike

我有一个模型:

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

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

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

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

update or delete on table "project" violates foreign key constraint {...} on table "historical_milestone" DETAIL: Key (id)=(123) is still referenced from table "historical_milestone".

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

If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

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

最佳答案

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)

关于django - Integrity_Error(键仍然被引用)即使在 on_delete=do_nothing 时也会抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33898841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com