How to Fix Django Migration Errors
In this tutorial, you'll learn about How to Fix Django Migration Errors. We cover key concepts, practical examples, and best practices.
Django raises migration errors when the migration files are out of sync with the database state, have conflicts, or contain operations that cannot be applied.
The Wrong Way
python manage.py migrate
This produces:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration app.0002_auto is applied to database without having migration app.0001_initial applied
The Right Way
Reset the migration state manually:
python manage.py migrate --fake app zero
python manage.py migrate --fake-initial
python manage.py migrate
Step-by-Step Fix
1. Check migration status
python manage.py showmigrations
This shows which migrations are applied and which are pending.
2. Fake a single migration
python manage.py migrate --fake app 0002_some_migration
3. Resolve dependency conflicts
Open the conflicting migration files and ensure dependencies match:
class Migration(migrations.Migration):
dependencies = [
('other_app', '0001_initial'), # this must exist
]
4. Reset an app's migrations completely
python manage.py migrate app zero
python manage.py makemigrations app
python manage.py migrate app
5. Create migrations from scratch (development only)
# Remove all migration files except __init__.py
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
# Drop the database tables
python manage.py migrate --fake app zero
# Recreate migrations
python manage.py makemigrations app
python manage.py migrate
Prevention Tips
- Never edit migration files manually after they have been applied.
- Always run
makemigrationsandmigratein the same command sequence. - Use
--mergewhen multiple migration branches exist. - Keep migration files in version control and apply them in the same order.
- Use
RunPythonoperations carefully and make them idempotent.
Common Mistakes with django migrations
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro