python - 删除时出现外键错误

标签 python mysql django django-models

我在 django 中有以下模型:

class ItemInstance(models.Model):
    item_type = models.ForeignKey('ItemContentType', related_name='item_type')
    name = models.CharField(max_length=256)

class TerritoryPricing(models.Model):
    item = models.ForeignKey(ItemInstance, null=True)
    territory = models.CharField(max_length=256)

但是,当我删除 ItemInstance 时,我总是会收到 IntegrityError。这是一个示例错误:

>>> ItemInstance.objects.filter(pk=123).delete()

IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (avails.main_territorypricing, CONSTRAINT main_territorypricing_ibfk_1 FOREIGN KEY (item_id) REFERENCES main_iteminstance (id))')

这最近才开始发生,所以我的 Django 应用程序或 Django 数据库中可能有一些缓存信息。我该如何解决这个问题?现在,我要做的是:

>>> TerritoryPricing.objects.filter(item__pk=123) # so no FK error
>>> ItemInstance.objects.filter(pk=123)

最佳答案

我认为您有引用完整性错误,因为 ForeignKey 没有为子行中的 FK 字段指定 on_delete 操作。尝试设置 on_delete=models.SET_NULL 例如,在删除相关对象后将 FK 字段设置为 NULL:

item = models.ForeignKey(ItemInstance, null=True, on_delete=models.SET_NULL)

您需要进行迁移并应用它们来更新数据库中的字段。

关于python - 删除时出现外键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867374/

相关文章:

python - Pandas.resample 为非整数倍频

python - 行走动画循环

python - Python 中嵌套列表的算术运算

mysql - Laravel 多态关系问题

mysql - 使用 MySQL 命令行,如何在 Select 语句中仅显示日期或金额(十进制)列?

带有 Logo 图像的 django pdf

python - cProfile 在调用 numba jit 函数时会增加大量开销

jquery - codeigniter jquery 依赖下拉菜单

django - 虚拟环境 : cannot access lib: No such virtualenv or site directory

python - Django 测试运行环境错误 : no enough space left on disk