How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Django · Python

Fix InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default' in Django

This error means a migration was applied out of order, usually because a custom user model was added after Django's admin migrations already ran. Fix it by resetting the migration state: clear the django_migrations table for the conflicting app, fake-apply the dependencies in order, then run migrate again.

Reading the Stack Trace

Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/venv/lib/python3.11/site-packages/django/core/management/base.py", line 412, in execute output = self.handle(*args, **options) File "/venv/lib/python3.11/site-packages/django/core/management/base.py", line 93, in wrapped res = handle_func(*args, **kwargs) File "/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 97, in handle self.check_consistent_history(connection) File "/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 334, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'.

Here's what each line means:

Common Causes

1. Custom user model added after initial migrate

You ran migrate before setting AUTH_USER_MODEL to a custom model, so admin.0001_initial was applied against the default User model.

# settings.py — added too late
AUTH_USER_MODEL = 'accounts.CustomUser'

# accounts/models.py
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    phone = models.CharField(max_length=20, blank=True)

2. Database copied from another project

The database was cloned from a different project that had different migration history, causing dependency mismatches.

# Copied production DB to local dev
$ pg_dump prod_db | psql local_db
$ python manage.py migrate
# Fails because local code has different migration graph

3. Squashed migrations with broken dependency chain

After squashing migrations, the dependency references were not updated to point to the squashed migration.

# accounts/migrations/0001_squashed_0005.py
class Migration(migrations.Migration):
    replaces = [
        ('accounts', '0001_initial'),
        ('accounts', '0002_add_phone'),
    ]
    dependencies = []  # Missing dependency on auth.0001_initial

The Fix

The cleanest fix in development is to drop the database and re-run migrations with the custom user model configured from the start. In production, you must carefully clear the conflicting rows from the django_migrations table and fake-apply them in the correct order.

Before (broken)
# settings.py — AUTH_USER_MODEL was set after running migrate
AUTH_USER_MODEL = 'accounts.CustomUser'

# Running: python manage.py migrate
# Raises InconsistentMigrationHistory
After (fixed)
# 1. Drop and recreate the database (development only)
$ dropdb myproject_db && createdb myproject_db

# 2. Ensure AUTH_USER_MODEL is set BEFORE first migrate
# settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'

# 3. Run migrations fresh
$ python manage.py migrate

Testing the Fix

import pytest
from django.core.management import call_command
from django.test import TestCase


class TestMigrations(TestCase):
    def test_migrations_are_consistent(self):
        """Ensure no migration conflicts exist."""
        try:
            call_command('migrate', '--check', verbosity=0)
        except SystemExit as e:
            if e.code != 0:
                pytest.fail('Unapplied migrations detected')

    def test_no_missing_migrations(self):
        """Ensure all model changes have migrations."""
        try:
            call_command('makemigrations', '--check', '--dry-run', verbosity=0)
        except SystemExit as e:
            if e.code != 0:
                pytest.fail('Model changes without migrations detected')

Run your tests:

pytest

Pushing Through CI/CD

git checkout -b fix/django-migration-inconsistency,git add accounts/migrations/ settings.py,git commit -m "fix: resolve migration dependency ordering for custom user model",git push origin fix/django-migration-inconsistency

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: test_db
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: python manage.py migrate --check
      - run: pytest --tb=short -q

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the full test suite locally to confirm migrations apply cleanly.
  2. Open a pull request with the migration fix.
  3. Wait for CI checks including the migrate --check step to pass.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify the deployment in staging before promoting to production.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that migrations apply cleanly on a fresh database before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

Yes. Delete the conflicting rows from the django_migrations table, then use python manage.py migrate --fake to re-record them in the correct order. This is necessary in production environments.

Always set AUTH_USER_MODEL before running your first migration. Add a CI step that runs migrate --check on a fresh database to catch ordering issues early.