I am building a django app with a MySQL DB. When I run \'python manage.py migrate\' for the first time, some tables are created well then some errors appear. The error broug
I met this problem while I use:
$ python manage.py test
If you didn't make migrations for those models which has a field that is a Foreignkey to django.contrib.auth.models.User, it will cause that problem.
And if you enabled --keepdb you will find there is no auth_user table and some other django's admin table.
Let's trace the whole problem:
run:
$ python manage.py test --verbosity=3
You can see the foreigngkey constraint exception raised after
Running deferred SQL...
the deferred sql is similar to
"ALTER TABLE
xxxADD CONSTRAINTxxFOREIGN KEY (x) REFERENCESauth_user"
check the source code of django/core/management/commands/migrate.py:
for statement in deferred_sql:
cursor.execute(statement)
The defered_sql comes from manifest.items() for loop,
and manifest comes from all_models,
and all_models comes from the app_config.label in app_labels.
this is the argument passed by
self.sync_apps(connection, executor.loader.unmigrated_apps)
Therefore, executor.loader.unmigrated_apps will contain the unmigrated_app's label, and if you happend to has a Foreignkey to Django's auth_user, it will cause Foreignkey constrain Error cause at the time, there is no table named auth_user.
solution:
suppose app is the module which contains those Foreignkey attributes class:
$ python manage.py migrate auth
$ python manage.py migrate
$ python manage.py makemigrations app
and, if you have other modules depend on the app, suppose the database tables have the same field with app module, you need:
$ python manage.py make migrate app --fake