[Django]-Django.db.utils.IntegrityError: 1452 'Cannot add or update a child row: a foreign key constraint fails

8👍

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', },

0👍

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

0👍

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', },
👤yomguy

0👍

backup the data in the table then delete the data from the table. Run migrations again it will work fine.

0👍

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.

Leave a comment