David542
David542

Reputation: 110227

Getting foreign key error on deletion

I have the following models in 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)

However, when I delete an ItemInstance, I always get an IntegrityError. Here is an example error:

>>> 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))')

This just started happening recently, so perhaps there is some cached information in my django app or django db. How can I go about fixing this? For now, what I have to do is:

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

Upvotes: 0

Views: 931

Answers (2)

David542
David542

Reputation: 110227

Do not have null=True in the Foreign Key definition, but rather have the model handle that itself:

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

This will fix the FK error you have above.

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78556

I think you have a referencial integrity error because the ForeignKey does not specify an on_delete action for the FK field in the child row. Try setting on_delete=models.SET_NULL for example, to set the FK field to NULL after deletion of the related object:

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

You'll need to make migrations and apply them to update the field in your DB.

Upvotes: 2

Related Questions