Django migrations, how to solve InconsistentMigrations error

Anahita Esfandiaryfard
3 min readDec 15, 2019

InconsistentMigrations error may happen while you try to run python manage.py migrate or makemigrations. Lots of reasons exists for this problem but usually, it happens when you are working in a big company in which there is more than one person work on the same project and different branches and they try to merge these branches. Searching google may not answer your question clearly or may show you solutions that terrifies you. But don’t panic! you don’t need to delete the entire database, re-run the project, lose all data or erase all migrations and recreate it again. Just be calm and follow these steps.

0: Make sure you have access to database. Then cd inside project directory and activate virtualenv

1: Run this command to see what migrations applied and what didn't

python manage.py showmigrations

as you can see in-migrated migrations has not x sign before them

2: Delete migration file(s) of the app which caused the problem. (eg: in following picture mobile)

3:Run command from step 1 to see what apps have failed migration. from the above list, you need to rollback migrate of the app with misapplied migration (eg: on above image gateway)

python manage.py — fake gateway zero

now you can migrate the app again :

python manage.py migrate gateway

but wait ! if you run this command you may face this error:

django.db.utils.OperationalError: (1050, “Table ‘gateway’ already exists”)

what to do?yes you need to delete all tables related to this app.Wait! you don't want too lose your data. So lets continue to next step.

4:Make a fixture from that app data.

If you don't know what a fixture is read about it here:https://docs.djangoproject.com/en/3.0/howto/initial-data/

Run:

python3 manage.py dumpdata gateway > gateway.json

Now drop that apps table from database.Then you can migrate you app successfully:

python manage.py migrate gateway

Now run showmigrations again to make sure your app migrated completely, then you can retrive you data back to your table using this command:

python3 manage.py loaddata gateway.json

Repeat these steps for other apps too.

5:While you have done, you can makemigrations for create new migration files and then migrate to migration files apply.

Done!Have Fun:)

--

--

Anahita Esfandiaryfard

I am python backend developer, I love data and currently I am master of data science in university of Catania