我在 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
, CONSTRAINTmain_territorypricing_ibfk_1
FOREIGN KEY (item_id
) REFERENCESmain_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/