Django: InconsistentMigrationHistory, applied before its dependency
The migration table records an order the graph forbids. Compare the rows with the files, then fake the gap, remove one row, or reset the database.

Introduction & Quick Summary
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default' means the django_migrations table records an order that the migration graph does not allow. Django builds a dependency graph from the migration files and compares it with what the database says was applied. When a migration is marked applied while something it depends on is not, the graph cannot be linearised and Django stops before running anything.
The four situations that produce it:
- A custom user model added after the first
migrate.admin.0001_initialdepends on the user model's migration, and the user app was swapped in afterwards. - A restored dump from another environment. The dump carries the table, but the files changed since it was taken.
--fakeused to unblock a deploy. The row exists, the dependencies were never applied.- Squashed migrations or renamed apps. A squash replaces several nodes, and an old row points at a node that no longer holds its dependency.
| Symptom | Reading | First step |
|---|---|---|
applied before its dependency | Order violation in django_migrations | showmigrations plus the migration file's dependencies |
Table 'x' already exists after clearing rows | Real DDL already ran | --fake-initial, not another delete |
| Only in one environment | That database's history differs | Compare django_migrations rows |
After adding AUTH_USER_MODEL | Built-in apps migrated first | Reset in development, plan a data migration in production |
Core Mechanics, Signatures & Reproducible Setup
Django stores one row per applied migration: (id, app, name, applied). On migrate, it loads every migration file, builds a directed graph, and checks that for each applied migration every dependency is either applied earlier or part of the same migration. A violation raises InconsistentMigrationHistory before any SQL runs, which is why the error lists two migrations and never a table.
The check is about recorded order, not about the schema. That distinction is what makes some repairs safe and others destructive: adding the missing rows changes the record, and whether the real schema matches is a separate question you answer with sqlmigrate or by inspecting the tables.
A minimal reproduction uses the built-in apps plus a custom user model introduced late:
# settings.py, added after the project already ran migrate once
AUTH_USER_MODEL = "accounts.User"python manage.py makemigrations accounts
python manage.py migratedjango.db.migrations.exceptions.InconsistentMigrationHistory: Migration
admin.0001_initial is applied before its dependency accounts.0001_initial
on database 'default'.admin.0001_initial was applied when the user model was still auth.User. Its dependency is now accounts.0001_initial, which has never run, and the history cannot be reordered after the fact.
Key Comparison Table
The repair depends on whether the schema already exists, so check that before choosing a command.
| Situation | Schema exists? | Safe command |
|---|---|---|
| Fresh development database | Partly | Delete the database file or drop the schema, then migrate |
| Production with real data | Yes, in full | migrate app --fake for the missing rows, or a hand-written migration |
| Table already created, migration not recorded | Yes | migrate --fake-initial |
| History from another environment | Yes | Diff the django_migrations rows, then fake the gap |
| Squashed migration replaced nodes | Yes | --fake the replacements, or keep replaces intact |
The commands differ by what they touch, worth keeping straight during an incident: migrate records and runs DDL, migrate --fake records without running it, migrate --fake-initial records only initial migrations whose tables exist, migrate app zero removes records and reverses DDL, and showmigrations --list reads state without changing anything.
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Read the history before touching it
Two commands give the whole picture: showmigrations for the applied state per app, and a query for the actual rows and their order. Do both, because showmigrations collapses squashed migrations and hides the row that is causing the conflict.
python manage.py showmigrations --list
python manage.py shell -c "
from django.db.migrations.recorder import MigrationRecorder
for row in MigrationRecorder.Migration.objects.order_by('id')[:20]:
print(row.id, row.app, row.name, row.applied)
"The migration file holds the dependency that is being violated:
# django/contrib/admin/migrations/0001_initial.py in the installed package
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("contenttypes", "0001_initial"),
]swappable_dependency is the reason the custom user model appears here: it resolves to whatever AUTH_USER_MODEL points at now, not at what it pointed at when the row was written.
The development reset, done correctly
On a local database with no data worth keeping, the deterministic fix is to remove the database and the generated migration files for the app you are changing, then regenerate. It is the only approach that guarantees the graph and the schema agree, and it is why teams keep seed fixtures.
rm db.sqlite3
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
python manage.py makemigrations
python manage.py migrateDo not run that find against third-party packages, and not at all on a database holding data you cannot regenerate. In a containerised stack, drop and recreate the schema instead: psql -c 'DROP SCHEMA public CASCADE; CREATE SCHEMA public;' followed by migrate.
Faking the missing dependency in production
When the schema is already correct and only the record is wrong, marking the dependency as applied is the smallest correct change. Take a backup of django_migrations first; it is the only thing you are editing.
pg_dump -t django_migrations app > django_migrations_backup.sql
python manage.py migrate accounts --fake
python manage.py showmigrations accounts admin--fake writes the row without running SQL, so verify the tables really exist before trusting it:
python manage.py sqlmigrate accounts 0001 | head -40
psql -U app -c "\d accounts_user"If the table exists with the expected columns, faking is honest. If it does not, faking buries the problem until the next query fails at runtime.
Removing a single bad row
Sometimes one row is the whole conflict, and deleting it lets migrate reapply cleanly. This is a surgical edit, so scope it to one migration by name:
DELETE FROM django_migrations
WHERE app = 'admin' AND name = '0001_initial';
SELECT app, name, applied FROM django_migrations
ORDER BY applied DESC LIMIT 10;Then python manage.py migrate --plan shows what Django intends to run, including the reapplication. --plan is the dry run people skip; without it, a delete followed by migrate can try to create tables that already exist.
--fake-initial and the "table already exists" case
--fake-initial marks an app's first migration as applied when all of its tables already exist. It is designed for databases created by syncdb before migrations existed, and it fits a restored dump whose migration record was not included.
python manage.py migrate --fake-initial
python manage.py migrate --planIt only inspects initial migrations, so it will not resolve a conflict in 0021_add_index. For those, the --fake route with an explicit app and migration name is the only recorded option.
Preventing the next occurrence
Two habits remove most of this class of failure: run makemigrations --check in CI so a missing migration fails the build instead of the deploy, and keep dependencies explicit in hand-written migrations rather than relying on run_before.
python manage.py makemigrations --check --dry-run
python manage.py migrate --planFor a project that already has users, adding a custom user model after the fact is a documented multi-step change, not a settings edit. Doing it in production means a separate data migration and a --fake step planned in advance; doing it in development means a reset.
Common Compilation/Runtime Mistakes & Version Gotchas
Deleting rows until the error disappears. Each delete changes the recorded state without regard to the schema. Follow every delete with migrate --plan and a table check.
Running migrate app zero in production to "start over". It reverses DDL and drops tables. On a populated database this is data loss, not a repair.
Editing migration files that are already applied. Changing dependencies in an applied migration makes the graph disagree with the rows in a new way. Add a new migration with the correct dependency instead.
Assuming showmigrations shows the real order. It shows state per app, not the global order, so a row applied early for a later dependency is invisible there.
Forgetting the second database. With a router and multiple databases, each database has its own django_migrations; the error names the alias (on database 'default'), so handle that one.
Mixing environments. Copying a production dump into staging without its migration records, or the reverse, is the most common origin of the inconsistency. Copy both tables or neither.
Version behaviour. The exception has existed since migrations arrived in Django 1.7; --fake-initial was added in 1.8; squashed migrations resolve replaces differently in modern releases, so a years-old squash may need --fake for its replacement nodes.
The error is a statement about recorded order, so the repair is always "make the record match the schema, then prove the schema matches the code". When you compare a production history with a staging one, the diff tool makes the row difference visible, and the SQL formatter keeps the diagnostic queries readable in the runbook.
Official references: django-admin migrate and Migrations.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesasyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry that fix it.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Using pytest.mark.parametrize for Parameterized Tests in Python
Learn how to use pytest.mark.parametrize to write parameterized tests in Python. Covers syntax, multiple arguments, fixtures, custom IDs, class/module-level use, and common pitfalls.
Django select_related and prefetch_related: Fix N+1 Queries
Learn how to eliminate N+1 queries in Django with select_related and prefetch_related, including practical examples, when to use each, and common pitfalls.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.