Multi-Database Migrations
Django-CFG provides two powerful commands for managing multi-database migrations.
migrate_all (Production)
State-validated migration of every database in DATABASES. It compares each database’s django_migrations table with the live schema before issuing any DDL, so a deploy fails loudly on drift instead of half-succeeding.
Usage
# Migrate all databases (runs makemigrations first)
python manage.py migrate_all
# Skip the makemigrations step
python manage.py migrate_all --skip-makemigrations
# Forensic check only: no DDL, no record changes; exit 1 on drift
python manage.py migrate_all --check
# Auto-repair detected drift (fake-apply / fake-rewind)
python manage.py migrate_all --repair
# CI mode: refuse every interactive prompt
python manage.py migrate_all --non-interactiveLifecycle (per database)
- Guards - the connection is live, a
TEST.MIRRORalias does not leak into a real run, no other migrate is running - Drift scan - finds migrations recorded but missing from the schema, and applied but unrecorded
- Repair - only with
--repair; otherwise drift is reported and that database stops - Execute - plain
migrate --database=<alias>, so Django and the router decide what applies - Verify - no migration is left pending for the apps that database owns
default is migrated first (cross-database FK targets exist before routed apps need them); the other aliases follow in alphabetical order. The run exits with status 1 when any database is not clean.
When to Use
Production deployments:
# CI/CD pipeline
python manage.py migrate_all --non-interactiveDocker entrypoint:
CMD python manage.py migrate_all --non-interactive && gunicornmigrator (Development)
Interactive wrapper around the same Migrator, with a menu and targeted runs.
Usage
# Full migration without prompts
python manage.py migrator --auto
# Interactive menu
python manage.py migrator
# One database alias only
python manage.py migrator --database trading_db
# One app, on every database that owns it
python manage.py migrator --app trading
# Allow auto-repair of drift
python manage.py migrator --auto --repair--app refuses to run when the app has no routing rule, so DDL is never pushed to a connection by guess.
Interactive Mode
Without a flag the command shows a menu:
django-cfg Migration Tool
Select an action:
> Run Full Migration (all DBs)
Run Full Migration with --repair
Check (forensic only, no DDL)
Create Migrations Only
Show DB Status
Migrate <alias> Only (one entry per non-default database)
ExitWhen to Use
Development:
python manage.py migrator --autoOne database:
python manage.py migrator --database trading_dbExploring status:
python manage.py migrator # pick "Show DB Status"Comparison
| Feature | migrate_all | migrator |
|---|---|---|
| Interactive menu | No | Yes (without --auto) |
Runs makemigrations | Yes (unless --skip-makemigrations) | Yes |
| Respects routing rules | Yes | Yes |
Forensic check (--check) | Yes | Menu entry |
| Specific database | No | --database |
| Specific app | No | --app |
| Best for | Production, CI/CD | Development, targeted migrations |
Standard Django Migrations
You can still use standard Django migration commands:
# Create migrations
python manage.py makemigrations
python manage.py makemigrations trading
# Migrate specific database
python manage.py migrate --database=trading_db
python manage.py migrate trading --database=trading_db
# Migrate all databases (respects routing)
python manage.py migrate
# Show migration status
python manage.py showmigrations
python manage.py showmigrations --database=trading_db
# Fake migration
python manage.py migrate --fake trading_db
# Rollback migration
python manage.py migrate trading 0001Migration Strategies
Initial Setup
# 1. Create migrations
python manage.py makemigrations
# 2. Migrate all databases
python manage.py migrate_all
# 3. Verify
python manage.py showmigrationsAdding New Model
# 1. Add model to apps/trading/models.py
# 2. Create migration
python manage.py makemigrations trading
# 3. Migrate trading database only
python manage.py migrator --database trading_dbProduction Deployment
# Pre-deployment check (no changes)
python manage.py migrate_all --check
# Deploy migrations
python manage.py migrate_all
# Verify
python manage.py showmigrationsRouting and Migrations
How Routing Affects Migrations
# settings.py
DATABASE_ROUTING_RULES = {
'trading': 'trading_db',
'wallet': 'wallet_db',
}Migration behavior:
- Trading app migrations → run on
trading_dbonly - Wallet app migrations → run on
wallet_dbonly - Other apps → run on
defaultdatabase
Migration Storage
Migrations are tracked in the django_migrations table in each database:
# Check migrations on specific database
python manage.py dbshell --database=trading_dbSELECT * FROM django_migrations WHERE app = 'trading';Troubleshooting
Migration Already Applied
# Fake the migration
python manage.py migrate --fake trading 0001 --database=trading_dbMigration Conflicts
# Check for conflicts
python manage.py makemigrations --check
# Merge migrations
python manage.py makemigrations --mergeReset Migrations (Development Only)
# Delete migration files (keep __init__.py)
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
# Drop and recreate databases, then
python manage.py migrate_allCross-Database Migration Errors
If you get relation does not exist errors:
# models.py - Add db_constraint=False for cross-database ForeignKeys
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
db_constraint=False # REQUIRED for cross-database FK
)Drift Detection and Repair
The django_migrator module is the engine behind both commands. Django trusts django_migrations and never compares it with the live schema, so manual hotfixes, partial restores and interrupted runs leave silent drift that later shows up as column does not exist or relation already exists.
Drift comes in two directions:
- recorded but missing:
django_migrationssays a migration ran, the schema disagrees - present but unrecorded: the schema already has the change,
django_migrationsdoes not
# See the drift without touching anything
python manage.py migrate_all --check
# Reconcile it: fake-apply what already exists, rewind what is missing, then migrate
python manage.py migrate_all --repairA run without --repair stops at a database that has drift and reports it; it never repairs silently.
Using the Migrator from code
from django_cfg.modules.django_migrator import (
Migrator,
MigratorOptions,
TextReportFormatter,
)
migrator = Migrator(options=MigratorOptions(repair=False, interactive=False))
report = migrator.check() # or migrator.migrate_all()
print(TextReportFormatter().render(report))
if not report.all_clean:
raise SystemExit(1)MigratorOptions fields: repair, dry_run, interactive, skip_makemigrations, verbosity.
Companion fields
Some fields (for example django_currency columns) add auto-generated columns that need no ALTER TABLE. Register a detector so the repair engine fake-applies them:
from django_cfg.modules.django_migrator import register_fake_detectorPrevention tips
- Do not hand-edit
django_migrations; usemigrate_all --repair. - Run
migrate_all --checkin CI before a deploy. - Keep one migrate running at a time per database; a concurrent-run guard stops a second one.
Best Practices
1. Always Create Migrations First
# ✅ Good
python manage.py makemigrations
python manage.py migrate_all
# ❌ Bad
python manage.py migrate_all # May fail if migrations don't exist2. Test Migrations Locally
# Test before production
python manage.py migrate_all --check3. Use migrate_all in CI/CD
# .github/workflows/deploy.yml
- name: Run migrations
run: python manage.py migrate_all --non-interactive4. Keep Migration History Clean
# Squash migrations periodically
python manage.py squashmigrations trading 0001 0010See Also
- Core Commands - migrate_all documentation
- Core Commands - migrator documentation
- Routing - Database routing details
- Multi-Database - Multi-database setup