Reputation: 2224
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?
Upvotes: 3
Views: 6494
Reputation: 141
This usually happens when you have a foreign key that reference a default that does not exist. l recommend you check if the object exist in the table that is adding the foreign key. If it does not exist change your default value that you are adding during migration to the one that exists, this can be done in migration files.
Upvotes: 0
Reputation: 141
backup the data in the table then delete the data from the table. Run migrations again it will work fine.
Upvotes: 0
Reputation: 76
I have resolved the same problem converting all the MyISAM type tables to InnoDB applying the SQL commands produced by this script:
SET @DATABASE_NAME = 'name_of_your_db';
SELECT CONCAT('ALTER TABLE `', table_name, '` ENGINE=InnoDB;') AS sql_statements
FROM information_schema.tables AS tb
WHERE table_schema = @DATABASE_NAME
AND `ENGINE` = 'MyISAM'
AND `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;
and then use this option in the django settings :
'OPTIONS' : { 'init_command' : 'SET storage_engine=InnoDB', },
Upvotes: 0
Reputation: 1
'OPTIONS' : { 'init_command' : 'SET storage_engine=MyISAM', }, <<-- This did not work for me but after cleaning the data in my database tables I want to modify it worked, though it's not a good approach to follow.
Upvotes: 0
Reputation: 2224
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', },
Upvotes: 8