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

标签 django orm

我有一个模型:

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/

相关文章:

python - 为什么 Django cms 站点地图 url 在所有浏览器中都不匹配?

sql - Django 中的复杂排序

javascript - Django-tinymce 不工作;获取一个普通的文本区域

Django ORM 查询数据月、日、年?

php - 理解 Laravel 中的 hasOne() 和 belongsTo() 函数

python - Django 使用主键列表来获取记录

java - JPA:AttributeConverter 的参数化实例

php - Controller 可以查看相关字段,但在添加或编辑操作中不显示它

java - 使用 AuditQuery 获取关联实体

java - 来自谷歌的 ORM