Skip to Content
DatabaseMigrations

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-interactive

Lifecycle (per database)

  1. Guards - the connection is live, a TEST.MIRROR alias does not leak into a real run, no other migrate is running
  2. Drift scan - finds migrations recorded but missing from the schema, and applied but unrecorded
  3. Repair - only with --repair; otherwise drift is reported and that database stops
  4. Execute - plain migrate --database=<alias>, so Django and the router decide what applies
  5. 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-interactive

Docker entrypoint:

CMD python manage.py migrate_all --non-interactive && gunicorn

migrator (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) Exit

When to Use

Development:

python manage.py migrator --auto

One database:

python manage.py migrator --database trading_db

Exploring status:

python manage.py migrator # pick "Show DB Status"

Comparison

Featuremigrate_allmigrator
Interactive menuNoYes (without --auto)
Runs makemigrationsYes (unless --skip-makemigrations)Yes
Respects routing rulesYesYes
Forensic check (--check)YesMenu entry
Specific databaseNo--database
Specific appNo--app
Best forProduction, CI/CDDevelopment, 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 0001

Migration Strategies

Initial Setup

# 1. Create migrations python manage.py makemigrations # 2. Migrate all databases python manage.py migrate_all # 3. Verify python manage.py showmigrations

Adding 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_db

Production Deployment

# Pre-deployment check (no changes) python manage.py migrate_all --check # Deploy migrations python manage.py migrate_all # Verify python manage.py showmigrations

Routing 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_db only
  • Wallet app migrations → run on wallet_db only
  • Other apps → run on default database

Migration Storage

Migrations are tracked in the django_migrations table in each database:

# Check migrations on specific database python manage.py dbshell --database=trading_db
SELECT * FROM django_migrations WHERE app = 'trading';

Troubleshooting

Migration Already Applied

# Fake the migration python manage.py migrate --fake trading 0001 --database=trading_db

Migration Conflicts

# Check for conflicts python manage.py makemigrations --check # Merge migrations python manage.py makemigrations --merge

Reset 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_all

Cross-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 )

See: Cross-Database Relations

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_migrations says a migration ran, the schema disagrees
  • present but unrecorded: the schema already has the change, django_migrations does 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 --repair

A 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_detector

Prevention tips

  • Do not hand-edit django_migrations; use migrate_all --repair.
  • Run migrate_all --check in 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 exist

2. Test Migrations Locally

# Test before production python manage.py migrate_all --check

3. Use migrate_all in CI/CD

# .github/workflows/deploy.yml - name: Run migrations run: python manage.py migrate_all --non-interactive

4. Keep Migration History Clean

# Squash migrations periodically python manage.py squashmigrations trading 0001 0010

See Also

Last updated on