Dmitrii Mikhailov
Dmitrii Mikhailov

Reputation: 5221

IntegrityError when delete model instance

I have two models like

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)

When I remove the A model instance, I get something like:

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".

I can't figure out why it happens, I thought FKs should be deleted by default.

Upvotes: 1

Views: 477

Answers (1)

Sam
Sam

Reputation: 2084

Try adding an on_delete argument to your recommendation field:

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)

Running 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})

You can read more about how Django handles foreign key deletion here.

Upvotes: 1

Related Questions