django.db.migrations.exceptions.InconsistentMigrationHistory

138,798

Solution 1

Your django_migrations table in your database is the cause of inconsistency and deleting all the migrations just from local path won't work.

You have to truncate the django_migrations table from your database and then try applying the migrations again. It should work but if it does not then run makemigrations again and then migrate.

Note: don't forget to take a backup of your data.

Solution 2

Since you are using a custom User model, you can first comment out

INSTALLED_APPS = [
...
#'django.contrib.admin',
...
]

in your Installed_Apps settings. Then run

python manage.py migrate.

When done uncomment

'django.contrib.admin'

Solution 3

Lets start off by addressing the issue with most of the answers on this page:

You never have to drop your database if you are using Django's migration system correctly and you should never delete migrations once they are comitted

Now the best solution for you depends on a number of factors which include how experienced you are with Django, what level of understanding you have of the migration system, and how valuable the data in your database is.

In short there are two ways you can address any migration error.

  1. Take the nuclear option. Warning: this is only an option if you are working alone. If other people depend on existing migrations you cannot just delete them.

    • Delete all of your migrations, and rebuild a fresh set with python3 -m manage makemigrations. This should remove any problems you had with dependencies or inconsistencies in your migrations.
    • Drop your entire database. This will remove any problems you had with inconsistencies you had between your actual database schema and the schema you should have based on your migration history, and will remove any problems you had with inconsistencies between your migration history and your previous migration files [this is what the InconsistentMigrationHistory is complaining about].
    • Recreate your database schema with python3 -m manage migrate
  2. Determine the cause of the error and resolve it, because (speaking from experience) the cause is almost certainly something silly you did. (Generally as a result of not understanding how to use the migration system correctly). Based on the error's I've caused there are three categories.

    1. Inconsistencies with migration files. This is a pretty common one when multiple people are working on a project. Hopefully your changes do not conflict and makemigrations --merge can solve this one, otherwise someone is going to have to roll back their migrations to the branching point in order to resolve this.
    2. Inconsistencies between your schema and your migration history. To manage this someone will have either edited the database schema manually, or deleted migrations. If they deleted a migration, then revert their changes and yell at them; you should never delete migrations if others depend on them. If they edited the database schema manually, revert their changes and then yell at them; Django is managing the database schema, no one else.
    3. Inconsistencies between your migration history and your migrations files. [This is the InconsistentMigrationHistory issue the asker suffers from, and the one I suffered from when I arrived at this page]. To manage this someone has either manually messed with the django_migrations table or deleted a migration after it was applied. To resolve this you are going to have to work out how the inconsistency came about and manually resolve it. If your database schema is correct, and it is just your migration history that is wrong you can manually edit the django_migrations table to resolve this. If your database schema is wrong then you will also have to manually edit that to bring it in line with what it should be.

Based on your description of the problem and the answer you selected I'm going to assume you are working alone, are new to Django, and don't care about your data. So the nuclear option may be right for you.

If you are not in this situation and the above text looks like gibberish, then I suggest asking the Django User's Mailing List for help. There are very helpful people there who can help walk you through resolving the specific mess you are in.

Have faith, you can resolve this error without going nuclear!

Solution 4

This happened to me in a new project after I added a custom User model, per the recommendation in the django docs.

If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you.

Here is what I did to solve the problem.

  1. Delete the database db.sqlite3.
  2. Delete the app/migrations folder.

Per @jackson, temporarily comment out django.contrib.admin.

INSTALLED_APPS = [
...
#‘django.contrib.admin’,
...
]

Also comment out the admin site in urls.py:

urlpatterns = [
    path('profile/', include('restapp.urls')),
    #path('admin/', admin.site.urls),
]

If you don't comment out the path('admin/'), you will get error "LookupError: No installed app with label 'admin'" when you run

python manage.py migrate

After the migrations finish, uncomment both of the above.

Solution 5

Here how to solve this properly.

Follow these steps in your migrations folder inside the project:

  1. Delete the _pycache_ and the 0001_initial files.
  2. Delete the db.sqlite3 from the root directory (be careful all your data will go away).
  3. on the terminal run:
      python manage.py makemigrations
      python manage.py migrate

Voila.

Share:
138,798
Hari Krishnan
Author by

Hari Krishnan

Putting a negative vote is easy and answering for each and every question is tough.I like to be the second kind. People are not here for your negative or positive vote. They are here for a solution. So folks,try to help them and try to learn from them.

Updated on May 08, 2022

Comments

  • Hari Krishnan
    Hari Krishnan almost 2 years

    When I run python manage.py migrate on my Django project, I get the following error:

    Traceback (most recent call last):
    File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
    File "/home/hari/project/env/local/lib/python2.7/site-     packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
    File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
    File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
    File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
    File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle
    executor.loader.check_consistent_history(connection)
    File "/home/hari/project/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 298, in check_consistent_history
    connection.alias,
    django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.
    

    I have a user model like below:

    class User(AbstractUser):
        place = models.CharField(max_length=64, null=True, blank=True)
        address = models.CharField(max_length=128, null=True, blank=True)
    

    How can I solve this problem?

    • Exprator
      Exprator almost 7 years
      first of all delete all the tables from the database, delete all the files from migrations folder except init.py then run migrate
    • Hari Krishnan
      Hari Krishnan almost 7 years
      how to delete all tables?
    • Exprator
      Exprator almost 7 years
      what db are you using?
    • Hari Krishnan
      Hari Krishnan almost 7 years
      yah. i have deleted it and now it is working.
    • Ruben Alves
      Ruben Alves over 3 years
      For me the problem was because I had a migration that depended on 'ipn', '__latest__'. I just checked the order or migrations applied with select * from django_migrations, then changed __latest__ by 'ipn', '0007_auto_20160219_1135' and the problem has gone away.
  • Airs
    Airs about 6 years
    For those interested: In my case, I had created a temporary migration to create tables in app B while I was waiting on my coworker to finish custom migrations to move the tables from app A to app B. When my coworker finished, I reverted my temporary migration and went to apply migrations. Bam error. Not only did I forget to unapply my temp migration, but had managed to name the temp migration the same as the actual one. To the migration system app B's 0001_initial migration which depended on app A's 00XX_auto migration had somehow been applied before it's dependency!
  • Airs
    Airs about 6 years
    As horrible as all that sounds it was easy to solve. My database did have the correct schema so all I had to do was manually add 'A' '00XX_auto' to the django_migrations table so my history reflected that the changes in that migration had been applied. Complicated, but not that hard once you work out the problem.
  • Collin Barrett
    Collin Barrett almost 6 years
    Could you add a summary of or quote from the linked article to your answer?
  • Iulian Pinzaru
    Iulian Pinzaru about 5 years
    Okay, what if I wouldn't like to drop my database ? Is there any available solution ?
  • Almenon
    Almenon about 5 years
    Didn't work. When I tried migrating it complained that a relation already exists. Note that you can truncate django_migrations table with this command: > python manage.py shell ``` from django.db import connection cursor = connection.cursor() cursor.execute("TRUNCATE TABLE django_migrations") ``` And you can view the migration table like this: ``` from django.db.migrations.recorder import MigrationRecorder MigrationRecorder.Migration.objects.all() ```
  • Szymon Przedwojski
    Szymon Przedwojski about 5 years
    Unfortunately this results in errors for me, e.g.: accounts.CustomUser.groups: (fields.E304) Reverse accessor for 'CustomUser.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'CustomUser.groups' or 'User.groups'.
  • Szymon Przedwojski
    Szymon Przedwojski about 5 years
    For me removing 'django.contrib.admin' from INSTALLED_APPS and running makemigrations results in LookupError: No installed app with label 'admin'.
  • Gautam Kumar
    Gautam Kumar almost 5 years
    go to urls.py and comment out urls with admin
  • mevaka
    mevaka almost 5 years
    Yes, this solved my problem! I was changed default user model to Abstract User model , and after all migrations gave error. But when tried this , solved my problem!
  • Deft-pawN
    Deft-pawN over 4 years
    It doesn't work for me. The error msg is "No install app with label admin", do I need to delete all files in migrtations firstly? anyone know how to solve it ? Thanks ~
  • JonPizza
    JonPizza over 4 years
    You can't just delete migrations, you need to delete the pycache too
  • Rexcirus
    Rexcirus over 4 years
    Check below for user9414732 answer.
  • cjm
    cjm over 4 years
    I got into this pickle because I had a bunch of non-Django tables of initial data so most of my models had managed = False in them. When I decided to let to ORM do its job and move to managed models (as a way of getting my tests to run), then all my "fun" started.
  • ZF007
    ZF007 over 4 years
    post code (replacement) in script form and on top where code starts each block starts with a file name representing a script. How you posted your answer is confusing to me.
  • Vladimir
    Vladimir about 4 years
    do not forget comment path('admin/', admin.site.urls) in urls.py
  • NaSir HuSSaiN
    NaSir HuSSaiN about 4 years
    @ZF007 Sorry for the confusion. I am a little bit new to StackOverflow, so i did not understand how to post an answer
  • Mike 'Pomax' Kamermans
    Mike 'Pomax' Kamermans almost 4 years
    You should absolutely delete migrations if your team decides to squash 0001 through 0230 or however-many-hundred-migrations you have: you commit the squashed migration, you wait for CI/CD to apply it, and once prod has fully caught up you delete the original 0001_... through 0230_... files because they do nothing anymore, and you back-update the squash migrations to no longer say it replaces anything. Keeping the old migrations around is only going to make dev life hell for your team when someone needs to figure out which of the umpteen 0002 migrations is the real one.
  • tbm
    tbm almost 4 years
    "anything weird or nuclear" and then "first just drop your database and rebuild it". If dropping the database isn't considered nuclear, I'd hate to see what is.
  • tbm
    tbm almost 4 years
    This is a terrible idea with a high likelihood of loss of data. See my answer below.
  • bob0the0mighty
    bob0the0mighty over 3 years
    While this may fix the problem, could you provide some information on why it will fix it as well?
  • moncef banouri
    moncef banouri over 3 years
    cuz u already created an sql database with a structure and some data in it and when u make some changes that could touch ur data and modify ur model it runder an error
  • Bishwas Bhandari
    Bishwas Bhandari over 3 years
    What if we don't want to delete and in production mode. Also I am not using sqllite, it's MySQL in our server. What's the better method without losing data.
  • Jairus
    Jairus over 3 years
    Some tips: try not to duplicate answers that already exist. There appears to be a selected solution already. If your answer is different, please elaborate on why, and provide more details if you can. For instance, what is the logic for comment on django.contrib.admin (also, do you mean comment out?). Why rerun the migration?
  • rray
    rray about 3 years
    Worked for me by following both suggestions. Thank you!
  • JHS
    JHS almost 3 years
    For fixing a local dev environment, this was the right solution for me - actually I just wiped out the whole DB, and it got recreated with all migrations ran fresh. My issue was I had run an old version of a 0001_initial migration previously and the new one was not applying. If you want a clean migration history for prod without unneeded changes, deleting and regenerating migrations in local dev before ever shipping those migrations to prod seems fine to me. Other comments and answers point out deleting/clearing migrations won't work for a prod database, which is true.
  • shahab_malekzade
    shahab_malekzade almost 3 years
    Your answer is the very nuclear b-o-m-b :))
  • Evan
    Evan almost 3 years
    This has helped me so many times (I always forget this). I would never have guessed the custom user model to be the issue given the error.
  • satvik.t
    satvik.t almost 3 years
    the safest answer! Thanks @kunshi
  • Ali Husham
    Ali Husham almost 3 years
    django.db.migrations.exceptions.InconsistentMigrationHistory‌​: Migration users.0001_initial is applied before its dependency auth.0012_alter_user_first_name_max_length on database 'default'. I have this and when I search for 0012_alter_user_first_name_max_length in my codde I find it in two diffrent apps
  • MarMat
    MarMat almost 3 years
    If your migrations are mixed up (dependency issues): use python manage.py showmigrations to see which migrations have been applied. Compare this with your django_migrations table in your database to see inconsistencies. Delete the entries from your django_migrations table that are out of order up to the dependency issue. Now, to fix the dependency, apply the migrations that are not yet reflected in the database to bring the database up to speed, and fake the ones that are already in the database to fix the migration history order. This only works if your migrations do not conflict. Tks @Airs
  • Mr Coder
    Mr Coder almost 3 years
    I have still issue can not fixed can help on same
  • inyang kpongette
    inyang kpongette over 2 years
    Please make sure to stop server if you already have the "runserver" command currently active. then delete the migration folder for your apps. If you have nothing to loose then maybe flush the db or delete it altogether, then run the migration command again.
  • chaudim
    chaudim over 2 years
    I also got the error msg "No install app with label admin" so i deleted the pycache folder in my migrations and it worked.
  • Bashar
    Bashar over 2 years
    that saves my ass, literally I thought it is not possible without wiping up the database but this trick worked!
  • Koops
    Koops over 2 years
    Only do if you dont mind deleting all your data!
  • Fathy
    Fathy over 2 years
    another quick way to do this is deleting the database if you're in development of course
  • Datajack
    Datajack about 2 years
    Only answer here that worked for me. Thanks.
  • Samuel Tosan Ayo
    Samuel Tosan Ayo about 2 years
    Perfect answer 😊
  • Mahdi Hamzeh
    Mahdi Hamzeh almost 2 years
    as the steps of squashing migrations explained in django documents,
  • Dr Phil
    Dr Phil almost 2 years
    As of 06/2022, I had a similar situation where I transitioned to a custom user model mid project. I am using postgres instead of sqlite, so the instructions are slightly different. But the idea is you have to delete local "migrations" as well as all database tables. If you want to save some data on your production server, you'll have to do it manually. Django documentation says basically the same thing.