Django – Can’t create table ‘.#sql-b74_b9’ (errno: 150)

Recently I got stucked at this issue so here I am sharing the work around that worked for me. The way I investigated the issue was quite generic so it should work in most of the cases.

Running djanog migrations is quite a very nice tool, however sometimes you just start facing strange error messages when running these migrations. This mostly happens when you run migrations across different machines or environments. Following is what you should follow in such cases:

First explore the sql statements that djanog is trying to execute in the background. You can get these sql statements using following:

python manage.py sqlmigrate <app_name> <migration_name>

The above command will simply dump the sql of a specific migration that you can copy.

If you are not sure about the migration name or if the migration name was not visible in the error messages, you will first need to know which migrations are being executed by django and then run the above command on each migration one by one. Use the following command to know which migrations are being executed:

python manage.py migrate --fake <service_name>

Above command runs the fake copy of migrations i.e. it shows you which migrations are being executed but does not execute them actually. From the output of this command, you can see a list of migrations. You can then ‘sqlmigrate’ each migration to see its sql dump.

Now when you have got access to the sql of migrations being run, you need to copy each migration’s sql and run it in MySQL (phpmyadmin for example) manually. By doing this you will eventually get the same error in MySQL console when you will reach running the erroneous migration. The benefit of doing this practice is that when you encounter an error in phpmyadmin, you also get detailed description about that error which you cannot see in django command line. By looking at the details of the error, chances are higher that you will find the actual issue and fix that. For example in my case one of the sql statement was renaming a table but the table was not implicitly renamed in a foreign key reference. Such details you can easily get when running the sql in phpmyadmin.

Leave a Reply

Your email address will not be published. Required fields are marked *