Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caot/d947a11330f2aff65aa6347c9a556123 to your computer and use it in GitHub Desktop.
Save caot/d947a11330f2aff65aa6347c9a556123 to your computer and use it in GitHub Desktop.
Fix mysql error 1005 when running django tests

#Django Test Database Error 1005 8/1/2015

Environment

  • Django 1.8.3
  • MySQL 5.5

When running python manage.py test I was receiving the following error

django.db.utils.OperationalError: (1005, "Can't create table 'test_xxx.#sql-####_##' (errno: 150)")

However this database error was unique to the test runner and was not occurring when running python manage.py migrate.

Research showed that MySQL error 1005 is an InnoDB specific error related to a malformed foreign key constraint (http://dev.mysql.com/doc/refman/5.0/en/innodb-error-codes.html)

I investigated and found this in the logs

mysql -u user -p
use test_xxx;
show engine innodb status;
...
------------------------
LATEST FOREIGN KEY ERROR
------------------------
150801 19:43:38 Error in foreign key constraint of table test_xxx/#sql-####_##:
FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`):
Cannot resolve table name close to:
(`id`)
...

Solution

The conclusion is that the auth_user table never gets created but a model has a foreign key field that references id from that table. This is a side effect of migrations being implemented into django 1.8. The solution is to make sure you have migrations for every app that has a foreign key field, good practice to have migrations for all apps.

python manage.py makemigrations <app_name>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment