How to Squash Migrations in Django: Step-by-Step Guide
To squash migrations in Django, use the
python manage.py squashmigrations app_label migration_name command to combine multiple migrations into one. This helps clean up your migration files while preserving database state.Syntax
The basic syntax to squash migrations is:
python manage.py squashmigrations <app_label> <migration_name>Here:
- app_label is the name of your Django app.
- migration_name is the name of the migration up to which you want to squash (usually the last migration).
bash
python manage.py squashmigrations myapp 0005Example
This example shows how to squash migrations for an app named blog up to migration 0004. It combines migrations 0001 to 0004 into a single migration file.
bash
python manage.py squashmigrations blog 0004Output
Created new squashed migration blog/migrations/0001_squashed_0004.py
You should review this migration for accuracy before applying.
Common Pitfalls
- Not reviewing the squashed migration: Always check the generated squashed migration file to ensure it correctly represents all changes.
- Squashing migrations with dependencies: If other apps depend on migrations you squash, you may need to adjust dependencies manually.
- Applying squashed migrations on existing databases: Existing databases with old migrations applied may cause conflicts; test carefully.
- Forgetting to delete old migrations: After squashing, remove old migration files to avoid confusion.
bash
## Wrong: Applying squashed migration without review python manage.py migrate ## Right: Review then migrate # 1. Run squashmigrations python manage.py squashmigrations blog 0004 # 2. Review generated file blog/migrations/0001_squashed_0004.py # 3. Delete old migrations 0001.py to 0004.py # 4. Run migrate python manage.py migrate
Quick Reference
- Use
squashmigrationsto combine migrations. - Review the generated squashed migration file carefully.
- Delete old migration files after squashing.
- Test migrations on a fresh database to avoid conflicts.
Key Takeaways
Use
python manage.py squashmigrations app_label migration_name to combine migrations.Always review the generated squashed migration file before applying it.
Delete old migration files after squashing to keep your project clean.
Test migrations on a fresh database to ensure no conflicts occur.
Be cautious with dependencies between apps when squashing migrations.