← Back to Django, page 4

django-0075 · Medium mid

How do squashmigrations, migration dependencies, merge migrations and RunSQL work in Django?

Each migration lists dependencies on earlier migrations, forming a graph. squashmigrations app 0001 0010 writes one migration with a replaces list that stands in for the originals until all environments have applied them, after which the old files can be deleted. If two branches create migrations with the same parent, makemigrations --merge creates a merge migration. RunSQL and RunPython hold hand-written changes and should be reversible.

Full answer

Migration files are nodes in a graph: dependencies = [("app", "0002_add_field")]. Django applies nodes in dependency order and records applied names in django_migrations.

Squashing: as an app collects hundreds of migrations, python manage.py squashmigrations app 0001 0010 creates 0001_squashed_0010_...py with replaces = [...]. Behaviour:

  • Databases that already applied all the replaced migrations are treated as having applied the squash; new databases run the single squashed migration.
  • Keep both sets of files until every environment has migrated past the squash, then delete the old files and the replaces line (and fix dependencies in other apps).
  • RunPython and RunSQL operations marked elidable=True are dropped during squashing. Others are kept, and a RunPython function defined inside a migration file cannot be copied safely: Django prints "Manual porting required" and the generated file refers to it with an invalid dotted path, so you must paste the function in by hand. Keeping data-migration functions in an importable helper module avoids this.
  • The squashed file is named 0001_squashed_0003_name.py, or 0001_initial_squashed_0003_name.py when it replaces an initial migration.
  • Squashing is an optimisation; do not do it while branches with unmerged migrations exist.

Conflicts: two developers add 0004_x and 0004_y from the same 0003. migrate fails with "Conflicting migrations detected". makemigrations --merge creates a migration depending on both leaves. Prefer rebasing and renumbering when the changes touch the same model.

Hand-written operations: migrations.RunSQL("CREATE INDEX ...", reverse_sql="DROP INDEX ...") for database features the ORM lacks, and RunPython(forward, backward). Use migrations.RunPython.noop as the reverse when nothing needs undoing. Use SeparateDatabaseAndState when the database change and Django's model state need to differ (for example renaming a table without a rename operation).

Useful commands: showmigrations, sqlmigrate app 0003, migrate app 0002 (roll back to a name), makemigrations --check, and migrate --plan.

python
import sys
import types

import io
import tempfile
from pathlib import Path

WORK = Path(tempfile.mkdtemp())
sys.path.insert(0, str(WORK))
pkg = WORK / "shopapp"
(pkg / "migrations").mkdir(parents=True)
(pkg / "__init__.py").write_text("")
(pkg / "migrations" / "__init__.py").write_text("")
(pkg / "models.py").write_text("""from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=40)
    sku = models.CharField(max_length=20, default="")
""")
(pkg / "migrations" / "0001_initial.py").write_text("""from django.db import migrations, models

class Migration(migrations.Migration):
    initial = True
    dependencies = []
    operations = [migrations.CreateModel("Product", [
        ("id", models.AutoField(primary_key=True, serialize=False)),
        ("name", models.CharField(max_length=40))])]
""")
(pkg / "migrations" / "0002_product_sku.py").write_text("""from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [("shopapp", "0001_initial")]
    operations = [migrations.AddField("Product", "sku", models.CharField(max_length=20, default=""))]
""")
(pkg / "seeding.py").write_text("""def seed(apps, schema_editor):
    apps.get_model("shopapp", "Product").objects.create(name="Notebook", sku="NB-1")
""")
(pkg / "migrations" / "0003_index_and_seed.py").write_text("""from django.db import migrations
from shopapp.seeding import seed

class Migration(migrations.Migration):
    dependencies = [("shopapp", "0002_product_sku")]
    operations = [
        migrations.RunSQL("CREATE INDEX shop_sku_idx ON shopapp_product (sku)", reverse_sql="DROP INDEX shop_sku_idx"),
        migrations.RunPython(seed, migrations.RunPython.noop),
    ]
""")

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["shopapp"] + ["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": str(WORK / "db.sqlite3")}},
)
django.setup()

from django.core.management import call_command

def run(*args, **kw):
    out = io.StringIO()
    call_command(*args, stdout=out, **kw)
    return out.getvalue().strip()

print(run("migrate", verbosity=0) or "migrated")
print(run("showmigrations", "shopapp"))
print([l for l in run("sqlmigrate", "shopapp", "0003").splitlines() if "CREATE INDEX" in l])
squash_log = run("squashmigrations", "shopapp", "0001", "0003", interactive=False)
print([line.strip() for line in squash_log.splitlines() if "Optimized" in line or "Manual porting" in line])

squashed = [p.name for p in (pkg / "migrations").glob("*squashed*.py")][0]
text = (pkg / "migrations" / squashed).read_text()
print(squashed)
print("replaces" in text, "RunSQL" in text, "RunPython" in text, "seeding" in text)
print(run("migrate", "shopapp", "0002", verbosity=0) or "rolled back to 0002")
print(run("showmigrations", "shopapp"))

Standalone script. It builds a small app named shopapp with three migrations in a temporary folder, then migrates, squashes and rolls back. A real project keeps these files under app/migrations/. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): migrated shopapp [X] 0001_initial [X] 0002_product_sku [X] 0003_index_and_seed ['CREATE INDEX shop_sku_idx ON shopapp_product (sku);'] ['Optimized from 4 operations to 3 operations.'] 0001_initial_squashed_0003_index_and_seed.py True True True True rolled back to 0002 shopapp [X] 0001_initial [X] 0002_product_sku [ ] 0003_index_and_seed

Key points

  • Migrations form a dependency graph recorded in django_migrations
  • Squash creates a migration with replaces; delete old files only when all environments are past it
  • makemigrations --merge resolves two leaf nodes
  • RunSQL and RunPython need reverse operations
  • sqlmigrate and migrate --plan show what will happen

Common mistakes

  • Deleting old migrations before every environment has applied them
  • Squashing while unmerged migration branches exist
  • Writing RunPython or RunSQL without a reverse operation
  • Resolving conflicts by editing numbers without checking dependencies

Follow-ups

  • How do you rename a table without losing data using SeparateDatabaseAndState?
  • What does migrate --fake do and when is it risky?
  • How do you safely roll back a data migration in production?

Tips

  • Describe the graph and django_migrations
  • Explain squash then clean up
  • Name RunSQL reverse_sql