patternpythondjangoModerate
Django migrations — managing schema drift and squashing
Viewed 0 times
Django 3.2+
migrationssquashschema driftshowmigrationsmakemigrationszero-downtime
Error Messages
Problem
Long-running projects accumulate hundreds of migration files, slowing down migrate and making history hard to follow. Unapplied migrations in production cause schema drift.
Solution
Squash migrations periodically with squashmigrations. Always run showmigrations in production before deploying. Use pre/post-deploy hooks to apply migrations safely.
# Check for unapplied migrations before deploy
python manage.py showmigrations --list
# Squash app migrations from 0001 to 0050 into a single file
python manage.py squashmigrations myapp 0001 0050
# Detect if models have unapplied changes (CI check)
python manage.py migrate --check # exits 1 if migrations needed
# Generate migration for a specific app only
python manage.py makemigrations myapp --name add_user_avatarWhy
Each migration file is a Python module that Django imports and executes in order. Squashing replaces many migrations with one equivalent migration, speeding up fresh installs. The original files stay until all deployments have applied the squash.
Gotchas
- Never delete migration files that haven't been applied in production — this causes django.db.utils.InconsistencyDetectedError
- After squashing, both old and squash migrations exist until the squash is fully applied everywhere — then old ones can be removed
- makemigrations --check is the correct CI gate — it returns exit code 1 when unapplied model changes exist
- SeparateDatabaseAndState is needed for zero-downtime migrations (add column with default, then remove default separately)
Context
Managing Django database migrations in production environments
Revisions (0)
No revisions yet.