django.db.utils.IntegrityError: 1452 'Cannot add or update a child row: a foreign key constraint fails


I’m trying to link a foreignKey on provider and a M2Mfield on bestbuy_type – however each time I try saving anything to either of these fields I get the error:

(1452, 'Cannot add or update a child row: a foreign key constraint fails (`savingschampion`.`products_masterproduct`, CONSTRAINT `provider_id_refs_id_2ea9c584` FOREIGN KEY (`provider_id`) REFERENCES `products_provider` (`id`))')

The fields are specified in my model as:

class MasterProduct(BaseModel):
    provider = models.ForeignKey('products.Provider', related_name = 'master_products', blank=True, null=True)
    bestbuy_type = models.ManyToManyField('products.BestBuy',blank=True, null=True)
    ...other (no relationship) fields which work fine

Using this does actually populate the correct values in django admin for the fields however the error is produced on the save.

Using MySQL and the engine specified is:

'ENGINE': 'django.db.backends.mysql'

Does anyone have any idea why this would be happening?


Turns out that the new tables being created were using InnoDB rather than MyISAM like the existing tables.

Adding this line to my Database config solved this for me by forcing the new tables created by South to use MyISAM:

'OPTIONS'  : { 'init_command' : 'SET storage_engine=MyISAM', },

Answered By – Jeff_Hd

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published