Skip to content

Instantly share code, notes, and snippets.

@rminderhoud
Created August 2, 2015 01:13
Show Gist options
  • Save rminderhoud/cd77ce75e741101f4bc7 to your computer and use it in GitHub Desktop.
Save rminderhoud/cd77ce75e741101f4bc7 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>

@ysymi
Copy link

ysymi commented Sep 19, 2016

Given analysis show us a good track of thought. but good practice is not work for me, I try:
python manage.py makemigrations auth
the output is
No changes detected in app 'auth'

but this works:

python manage.py migrate auth
python manage.py migrate

my env:

  • python 2.7.10
  • django: 1.8
  • mariadb: 5.5.49

@shesl-meow
Copy link

It works!!!!!

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