django.db.migrations.exceptions.InconsistentMigrationHistory
Asked Answered
C

37

200

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?

Chorea answered 20/6, 2017 at 11:25 Comment(7)
first of all delete all the tables from the database, delete all the files from migrations folder except init.py then run migrateHardwood
how to delete all tables?Chorea
what db are you using?Hardwood
yah. i have deleted it and now it is working.Chorea
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.Rackety
@Hardwood what database?Woodwork
@Hardwood Should I delete db.sqlite3?Woodwork
W
75

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.

Weitzel answered 20/6, 2017 at 11:31 Comment(3)
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() ```Zora
This is a terrible idea with a high likelihood of loss of data. See my answer below.Ginnygino
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.Rolanda
H
244

Since you are using a custom User model, you can do these 4 steps:

  1. Comment out django.contrib.admin in your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
   ...
   #'django.contrib.admin',
   ...
]
  1. Comment out the admin path in urls.py:
urlpatterns = [
   ...
   #path('admin/', admin.site.urls) 
   ...
]
  1. Then run:
 python manage.py makemigrations  # (optional)
 python manage.py migrate
  1. When you are done, uncomment it all back
Headwards answered 27/1, 2018 at 13:12 Comment(11)
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!Overreach
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 ~Effusion
Check below for user9414732 answer.Addressograph
do not forget comment path('admin/', admin.site.urls) in urls.pyMinette
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.Companionship
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.Uranic
I also got the error msg "No install app with label admin" so i deleted the pycache folder in my migrations and it worked.Melody
another quick way to do this is deleting the database if you're in development of courseCommodore
this worked for me. i commented the django.contrib.admin in project's settings.py and also commend the admin path in project's urls.py, did python manage.py migrate then uncommented the previously commented codes.Gladisgladney
I get LookupError: No installed app with label 'admin'.Woodwork
It worked. but why did it happened? (i've initially migrated and created superuser then i tried to use custom user model)Resoluble
E
130

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!

Etch answered 19/4, 2018 at 1:4 Comment(8)
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!Etch
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.Etch
You can't just delete migrations, you need to delete the pycache tooVoorhis
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.Kelsey
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.Paramount
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 @EtchPicket
as the steps of squashing migrations explained in django documents,Coexist
Solution 2.3 worked for me, but I had to figure out the best way to modify django_migrations, which imho is not with a truncate. My specific use case: I built an app using the native User model (auth_user table), and having 2 apps (admin + allauth) depending on it. 1y later I extend AbstractUser creating a CustomUser model still based on auth_user. makemigrations failed with InconsistentMigrationHistory. Solution: INSERT INTO django_migrations(app, name, applied) VALUES ('myapp', '0001_initial', <timestamp just preceding admin and account 0001_initial migrations timestamp>);Patsypatt
W
75

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.

Weitzel answered 20/6, 2017 at 11:31 Comment(3)
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() ```Zora
This is a terrible idea with a high likelihood of loss of data. See my answer below.Ginnygino
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.Rolanda
D
75

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.

Decagram answered 26/8, 2019 at 0:17 Comment(1)
I never deleted the db.sqlite3. I only commented out #‘django.contrib.admin’, and #path('admin/', admin.site.urls),. Didn't need to delete db.sqlite3, it worked anyways.Woodwork
B
73

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.

Barnhill answered 24/9, 2017 at 12:18 Comment(3)
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.Grainy
Only answer here that worked for me. Thanks.Ginetteginevra
Perfect answer 😊Copalite
S
41

Problem

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.

So we can migrate database without admin(admin.0001_initial) firstly.

After its dependency migrated, execute commands to migrate admin.0001_initial.

Solution

  1. remove 'django.contrib.admin' from INSTALLED_APPS in settings.py.
  2. execute commands:

Python manage.py makemigrations appname

Python manage.py migrate appname

  1. add 'django.contrib.admin' to INSTALLED_APPS in settings.py file.
  2. execute commands again:

Python manage.py makemigrations appname

Python manage.py migrate appname

Spathic answered 24/9, 2018 at 7:25 Comment(5)
For me removing 'django.contrib.admin' from INSTALLED_APPS and running makemigrations results in LookupError: No installed app with label 'admin'.Overcompensation
go to urls.py and comment out urls with adminUria
Worked for me by following both suggestions. Thank you!Cara
the safest answer! Thanks @kunshiUmbrage
that saves my ass, literally I thought it is not possible without wiping up the database but this trick worked!Wadesworth
G
11

Before performing any other steps, back up your database. Then back it up again.

Remove any custom user model code out of the way, disable your custom model and app in settings, then:

python manage.py dumpdata auth --natural-primary --natural-foreign > auth.json
python manage.py migrate auth zero  # This will also revert out the admin migrations

Then add in your custom model, set it in settings, and re-enable the app. Make sure you have no migrations on this app yet.

Then:

python manage.py makemigrations <your-app>
python manage.py migrate
python manage.py loaddata auth.json  # Assumes your user-model isn't TOO dissimilar to the standard one.

Done!

Ginnygino answered 5/6, 2020 at 16:16 Comment(0)
M
10

Solved by commenting app admin before migration in settings.py

django.contrib.admin

and in urls.py,

('admin/', admin.site.urls)

uncomment after migrate

Micro answered 7/1, 2020 at 18:28 Comment(2)
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.Amphichroic
@Amphichroic Sorry for the confusion. I am a little bit new to StackOverflow, so i did not understand how to post an answerMicro
D
6

Just delete all the migrations folders, __pycache__, .pyc files:

find . | grep -E "(__pycache__|\.pyc|\.pyo$|migrations)" | xargs rm -rf

then, run:

python manage.py makemigrations
python manage.py migrate
Dowdy answered 23/3, 2021 at 10:56 Comment(2)
I have still issue can not fixed can help on sameHuebner
Heads UP ! This command will also remove Django's default migrationsHolytide
E
5

When you are doing some changes to default user model or you are making a custom user model by abstractuser then lot of times you will face that error

1: Remember when we create a superuser then for logging in we need username and password but if you converted USERNAME_FIELD = 'email' then now you can't login with username and password because your username field is converted into email....

So Now it will show like this :

and if you try to make another superuser then it will not ask for username it will only ask for email and password and then after creating superuser by email and password only when you try to login in admin pannel then it will throw that error because there is not any username and username field is required Error while creating superuser

2: That's why after creating custom user model during migrate it will throw error so for resolving it first add AUTH_USER_MODEL = 'appname.custommodelname' (appname is the app name where you definded your custom user model and custom model name is the name of the model which you gave to your custom user model) in your settings.py 3: Then delete the migrations folder of that app where you created that custom user model then delete the database db.sqlite3 of the project 4: Now run migrations python manage.py makemigrations appname(that app name where you defined your custom user model) 5: Then Migrate it by python manage.py migrate 6: That's it Now it is Done

Encyst answered 29/5, 2021 at 8:31 Comment(1)
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.Maintop
R
4

You can delete directly db.sqlite3, then migrate a new database is automatically generated. It should fix it.

rm sqlite3.db

python manage.py makemigrations
python manage.py migrate
Russophobe answered 23/11, 2021 at 21:33 Comment(1)
Only do if you dont mind deleting all your data!Russophobe
C
3

In my case the problem was with pytest starting, where I just altered --reuse-db to --create-db, run pytest, and changed it back. This fixed my problem

Cod answered 7/11, 2021 at 19:39 Comment(0)
S
3

How to fix (Without delete migration folder or entire database)

  1. Backup your database
  2. Comment out your app in INSTALLED_APPS and AUTH_USER_MODEL = 'account.User' in your settings.py
  3. python manage.py admin zero
  4. Undo step 2
  5. python manage.py migrate

Why this problem occured?

django admin app depends on AUTH_USER_MODEL which is default auth model when you create your django project.

If you migrate project models before change the AUTH_USER_MODEL, django admin app apply migration as django auth model dependency. However, you change that dependency and want to migrate models again. So, the problem is occured here; admin models applied before its dependency, which is your User model now, applied. Thus, You should revert admin models migrations and then try it again.

Susi answered 5/3, 2022 at 18:10 Comment(1)
python manage.py admin zero - what is that supposed to mean? Typo?Incogitable
D
2

just delete the sqlite file or run flush the databse 'python manage.py flush' and then run makemigrations and migrate commands respectively.

De answered 14/10, 2018 at 2:21 Comment(0)
Y
2

when you create a new Django project and run

python manage.py migrate

The Django will create 10 tables for you by default including one auth_user table and two start with auth_user.

when you want to create a custom user model inherit from AbstractUser, you will encounter this problem with error message as follow:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.

I solve this problem by dropping my entire database, and create a new one. And this replaced the three tables I mentioned.

Yepez answered 11/12, 2018 at 13:55 Comment(1)
Okay, what if I wouldn't like to drop my database ? Is there any available solution ?Martres
O
2

Your Error is essentially:

Migration "B" is applied before its dependency "A" on database 'default'.

Sanity Check: First, open your database and look at the records in the 'django_migrations' table. Records should be listed in Chronological order (ex: A,B,C,D...).

Make sure that the name of the "A" Migration listed in the error matches the name of the "A" migration listed in the database. (They can differ if you had previously, manually, edited or deleted or renamed migration files)

To Fix This, rename migration A. either in the database or rename the filename. BUT make sure the changes matches up with what other developers on your team have in their databases (or the changes matches what on your production database)

Outshoot answered 23/5, 2019 at 15:35 Comment(0)
O
2

The order of INSTALLED_APPS seems important. If you always put your recent works on top/beginning of the list they'll always be loaded properly in regard to django.contrib.admin. Moving my works to the beginning of the INSTALLED_APPS list fixed this problem for me. The reason Kun Shi's solution may have worked maybe it ran the migrations in a different order.

Oklahoma answered 16/8, 2020 at 1:28 Comment(0)
C
1

There is another reason besides user error that can lead to this sort of problem: a known issue with Django when it comes to squashed migrations.

We have a series of migrations that work perfectly fine in Python 2.7 + Django 1.11. Running makemigrations or migrate always works as it should, etc., even (for the purpose of testing) when the database is freshly re-created.

However, as we move a project to Python 3.6 (currently using the same Django 1.11) I've been stuck trying to figure out why the same migrations apply just fine only the first time they are run. After that, any attempt to run makemigrations or even just migrate results in the error:

django.db.migrations.exceptions.InconsistentMigrationHistory

wherein migration foo.0040-thing is applied before its dependency foo.0038-something-squashed-0039-somethingelse (we only happen to have that one squashed migration... the rest are much more straightforward).

What's bugged me for a while is why this only happens on Python 3. If the DB is truly inconsistent this should be happening all the time. That the migrations appear to work perfectly fine the first time they are applied was equally confounding.

After much searching (including the present Q&A thread), I stumbled upon the aforementioned Django bug report. Our squash migration did indeed use the b prefix in the replaces line (e.g., replaces = [(b'', 'foo.0038-defunct'),.......]

Once I removed the b prefixes from the replaces line it all worked normally.

Cheremkhovo answered 9/4, 2019 at 1:13 Comment(0)
R
1

If you are working on an empty database a quick fix could be running the migrations for the account app, before any other app migrations.

$ ./manage.py migrate account

And then:

$ ./manage.py migrate
Renowned answered 1/7, 2019 at 13:24 Comment(0)
B
1

I have to drop my database to and then run makemigrations and migrate again for this to be resolved on my part.

Bottom answered 20/6, 2020 at 6:28 Comment(0)
N
1

These steps can as well work

  1. Drop your entire database
  2. Make a new migration

These few steps can solve it for you, and I think its best when you have multiple contributors to the sam project.

Nuptial answered 21/11, 2021 at 0:58 Comment(0)
H
1

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

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

in your Installed_Apps settings. And also comment

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

in your base urls.py

Then run

python manage.py migrate.

When done uncomment

'django.contrib.admin'

and

path('admin/', admin.site.urls)
Helmsman answered 8/5, 2022 at 8:17 Comment(0)
Z
1

In my case, I was also using a custom user. the following steps work for me.

1 - delete all migrations and database tables (If you have testing data !!!!).

2 - Run migrations for the custom user app.

python manage.py makemigrations customAuth
python manage.py migrate customAuth

3 - Then run migration for the project level.

python manage.py makemigrations
python manage.py migrate
Zumwalt answered 29/10, 2022 at 5:44 Comment(0)
N
0

First delete all the migrations and db.sqlite3 files and follow these steps:

$ ./manage.py makemigrations myapp 
$ ./manage.py squashmigrations myapp 0001(may be differ)

Delete the old migration file and finally.

$ ./manage.py migrate
Nitroglycerin answered 13/1, 2018 at 12:28 Comment(0)
T
0

If that exception was reveal itself while you are trying to create your own User model instead of standard follow that instruction
I have found my problem resolve by follow that instruction step by step:

  1. Create a custom user model identical to auth.User, call it User (so many-to-many tables keep the same name) and set db_table='auth_user' (so it uses the same table)
  2. Throw away all your migrations
  3. Recreate a fresh set of migrations
  4. Sacrifice a chicken, perhaps two if you're anxious; also make a backup of your database
  5. Truncate the django_migrations table
  6. Fake-apply the new set of migrations
  7. Unset db_table, make other changes to the custom model, generate migrations, apply them

It is highly recommended to do this on a database that enforces foreign key constraints. Don't try this on SQLite on your laptop and expect it to work on Postgres on the servers!

Trilateral answered 30/5, 2018 at 13:42 Comment(1)
Could you add a summary of or quote from the linked article to your answer?Econometrics
I
0

If you set AUTH_USER_MODEL in settings.py like this:

AUTH_USER_MODEL = 'custom_user_app_name.User'

you should comment this line before run makemigration and migrate commands. Then you can uncomment this line again.

Intramural answered 30/9, 2018 at 12:41 Comment(1)
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'.Overcompensation
Y
0

when you create a new project and with no apps, you run the

python manage.py migrate

the Django will create 10 tables by default.

If you want create a customer user model which inherit from AbstractUser after that, you will encounter this problem as follow message:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.

finally, I drop my entire databases and run

Yepez answered 11/12, 2018 at 13:45 Comment(0)
O
0

I encountered this when migrating from Wagtail 2.0 to 2.4, but have seen it a few other times when a third party app squashes a migration after your current version but before the version you’re migrating to.

The shockingly simple solution in this case at least is:

./manage.py migrate
./manage.py makemigrations
./manage.py migrate

i.e. run a single migrate before trying to makemigrations.

Orthogenesis answered 2/4, 2019 at 4:9 Comment(0)
S
0

This Problem will come most of the time if you extend the User Model post initial migration. Because whenever you extend the Abstract user it will create basic fields which were present un the model like email, first_name, etc.

Even this is applicable to any abstract model in django.

So a very simple solution for this is either create a new database then apply migrations or delete [You all data will be deleted in this case.] the same database and reapply migrations.

Sicken answered 25/6, 2019 at 10:20 Comment(0)
D
0

delete migrations folder and db.sqlite3 and type in the cmd python manage.py makemigrations

Deplane answered 14/8, 2020 at 14:17 Comment(2)
While this may fix the problem, could you provide some information on why it will fix it as well?Tuggle
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 errorDeplane
T
0

django.db.migrations.exceptions.InconsistentMigrationHistory #On Creating Custom User Model

I had that same issue today, and none of the above solutions worked, then I thought to erase all the data from my local PostgreSQL database using this following command

-- Drop everything from the PostgreSQL database.

DO $$
DECLARE
        q TEXT;
        r RECORD;
BEGIN
        -- triggers
        FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
                FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pt.tgisinternal=false
            ) LOOP
                EXECUTE format('DROP TRIGGER %I ON %I.%I;',
                    r.tgname, r.nspname, r.relname);
        END LOOP;
        -- constraints #1: foreign key
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype='f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- constraints #2: the rest
        FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
                FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pcon.contype<>'f'
            ) LOOP
                EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
                    r.nspname, r.relname, r.conname);
        END LOOP;
        -- indicēs
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='i'
            ) LOOP
                EXECUTE format('DROP INDEX %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- normal and materialised views
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind IN ('v', 'm')
            ) LOOP
                EXECUTE format('DROP VIEW %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- tables
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='r'
            ) LOOP
                EXECUTE format('DROP TABLE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- sequences
        FOR r IN (SELECT pns.nspname, pc.relname
                FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
                WHERE pns.oid=pc.relnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pc.relkind='S'
            ) LOOP
                EXECUTE format('DROP SEQUENCE %I.%I;',
                    r.nspname, r.relname);
        END LOOP;
        -- extensions (only if necessary; keep them normally)
        FOR r IN (SELECT pns.nspname, pe.extname
                FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
                WHERE pns.oid=pe.extnamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
            ) LOOP
                EXECUTE format('DROP EXTENSION %I;', r.extname);
        END LOOP;
        -- aggregate functions first (because they depend on other functions)
        FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
                    AND pagg.aggfnoid=pp.oid
            ) LOOP
                EXECUTE format('DROP AGGREGATE %I.%I(%s);',
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- routines (functions, aggregate functions, procedures, window functions)
        IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='prokind' -- PostgreSQL 11+
            ) THEN
                q := 'CASE pp.prokind
                        WHEN ''p'' THEN ''PROCEDURE''
                        WHEN ''a'' THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
                WHERE attrelid='pg_catalog.pg_proc'::regclass
                    AND attname='proisagg' -- PostgreSQL ≤10
            ) THEN
                q := 'CASE pp.proisagg
                        WHEN true THEN ''AGGREGATE''
                        ELSE ''FUNCTION''
                    END';
        ELSE
                q := '''FUNCTION''';
        END IF;
        FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
                FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
                WHERE pns.oid=pp.pronamespace
                    AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
            ' LOOP
                EXECUTE format('DROP %s %I.%I(%s);', r.pt,
                    r.nspname, r.proname,
                    pg_get_function_identity_arguments(r.oid));
        END LOOP;
        -- nōn-default schemata we own; assume to be run by a not-superuser
        FOR r IN (SELECT pns.nspname
                FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
                WHERE pr.oid=pns.nspowner
                    AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
                    AND pr.rolname=current_user
            ) LOOP
                EXECUTE format('DROP SCHEMA %I;', r.nspname);
        END LOOP;
        -- voilà
        RAISE NOTICE 'Database cleared!';
END; $$;

After this you can run django command for migrations

python manage.py makemigrations
python manage.py migrate

And Absolutely that will work . Thank You.

Twilley answered 16/10, 2020 at 7:20 Comment(0)
H
0

How to solve a weird InconsistentMigrationHistory issue in production

The logs looked like it worked fine:

>>> ./manage migrate
====== Migrations =====
Running migrations:
  Applying app.0024_xxx... OK
  Applying app.0025_yyy... OK

But then

>>> ./manage migrate
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration app.0025_yyy is applied before its dependency app.0024_xxx on database 'default'.

How to solve? Change dependency of app.0025_yyy.py manually from 0024_xxx to 0023_prior_migration_name Then:

>>> ./manage.py makemigrations --merge
Created new merge migration /app/src/app/migrations/0026_merge_20220809_1021.py
>>> ./manage.py migrate
Running migrations:
  Applying app.0024_xxx... OK
  Applying app.0026_merge_20220809_1021... OK

This solves the issue, but if you do not want to commit your changes you can just revert everything by doing:

>>> ./manage.py migrate app 0023
Running migrations:
  Rendering model states... DONE
  Unapplying app.0026_merge_20220809_1021... OK
  Unapplying app.0024_xxx... OK
  Unapplying app.0025_yyy... OK

Revert dependency change of 0025_yyy and delete merge migration.

>>> ./manage migrate
====== Migrations =====
Running migrations:
  Applying app.0024_xxx... OK
  Applying app.0025_yyy... OK
Hardi answered 9/8, 2022 at 8:43 Comment(0)
B
0

For me, I wrote this line:

AUTH_USER_MODEL = 'myApp.CustomUser'

after INSTALLED_APPS, and this solved the problem.

Bushcraft answered 16/9, 2023 at 19:50 Comment(0)
C
0

If nothing works, and you are sure the issue is not because of inconsistent migration but because of auth model residing in a different db, then you can try suppressing the error message itself,

lib/python2.7/site-packages/django/db/migrations/loader.py", line 298, in check_consistent_history

Here ,in the method check_consistenst_history, return before the migrations history is checked.

    def check_consistent_history(self, connection):
       """
       Raise InconsistentMigrationHistory if any applied migrations have
       unapplied dependencies.
       """
       return
    
       recorder = MigrationRecorder(connection)
       applied = recorder.applied_migrations()
       for migration in applied:
           # If the migration is unknown, skip it.
           if migration not in self.graph.nodes:
          

Ofcourse, please proceed with caution and this should be the last resort if nothing works.

Cortisone answered 20/3 at 6:48 Comment(0)
P
-1

first of all backup your data. (copy your db file).

delete sqlite.db and also the migration folder.

then, run these commands:

./manage.py makemigrations APP_NAME
./manage.py migrate APP_NAME

after deleting the DB file and migration folder make sure that write the application name after the migration commands.

Punt answered 10/4, 2020 at 17:58 Comment(0)
F
-1

Okay, before you do anything weird or nuclear, first just drop your database and rebuild it.

If using POsgres -

DROP SCHEMA public CASCADE;
CREATE SCHEMA PUBLIC;

Then just remake your migrations

./manage.py migrate

This is the most basic solution, which typically will clear things up. Don't just go remaking the migrations until absolutely neccessary.

Ferryman answered 13/4, 2020 at 18:31 Comment(3)
"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.Ginnygino
Your answer is the very nuclear b-o-m-b :))Spermophyte
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 appsHostess
D
-1

Comment django.contrib.admin from installed apps and also comment path('admin/', admin.site.urls),then rerun makemigrations and then migrate. It will solve your issue. For more info go here

Davie answered 23/12, 2020 at 16:44 Comment(1)
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?Zorine

© 2022 - 2024 — McMap. All rights reserved.