删除模型实例时的IntegrityError

时间:2017-12-27 14:24:37

标签: python django django-models

我有两个模型,如

class A(models.Model):
   title = models.CharField(max_length=255)

class B(models.Model):
   recommendation = models.ForeignKey(A, related_name="+")
   title = models.CharField(max_length=255)

当我删除A模型实例时,我会得到类似的内容:

IntegrityError: update or delete on table "myapp_a" violates foreign key constraint "myapp_relate_recommendation_id_4a7c5340_fk_myapp_a_id" on table "myapp_b"
Detail: Key (id)=(27527) is still referenced from table "myapp_b".

我无法弄清楚为什么会发生这种情况,我认为默认情况下应该删除FK。

1 个答案:

答案 0 :(得分:1)

尝试在on_delete字段中添加recommendation参数:

<强> models.py

class A(models.Model):
   title = models.CharField(max_length=255)

class B(models.Model):
   recommendation = models.ForeignKey(A, related_name="+", on_delete=models.CASCADE)
   title = models.CharField(max_length=255)

正在运行python manage.py shell

>>> from abtest.models import A, B
>>> a = A(title="test A title")
>>> a.save()
>>> a
<A: A object (1)>
>>> b = B(title="test B title", recommendation=a)
>>> b.save()
>>> b
<B: B object (1)>
>>> b.recommendation
<A: A object (1)>
>>> a.delete()
(2, {'abtest.B': 1, 'abtest.A': 1})

您可以阅读有关Django如何处理外键删除here的更多信息。