← Back to Django, page 2

django-0026 · Medium mid

How do you write a data migration in Django with RunPython, and what rules should it follow?

Create an empty migration with makemigrations --empty app, then add migrations.RunPython(forward, backward). Inside the functions, get models with apps.get_model("app", "Model") so you use the historical version that matches that point in history, not the current class. Provide a reverse function (or RunPython.noop), batch large updates, and keep schema and data changes in separate migrations on databases that cannot mix them in one transaction.

Full answer

Schema migrations change tables. Data migrations change rows, for example filling a new full_name field from first_name and last_name, or converting grades "A/B/C" to marks ranges.

Steps:

  1. python manage.py makemigrations school --empty --name fill_full_name
  2. Edit the file:
python
def forwards(apps, schema_editor):
    Student = apps.get_model("school", "Student")
    for s in Student.objects.filter(full_name=""):
        s.full_name = f"{s.first_name} {s.last_name}".strip()
        s.save(update_fields=["full_name"])

class Migration(migrations.Migration):
    dependencies = [("school", "0004_student_full_name")]
    operations = [migrations.RunPython(forwards, migrations.RunPython.noop)]

Rules:

  • Use apps.get_model(). Importing from school.models import Student gives you today's model, which may have fields that do not exist yet at this migration. Historical models also have no custom methods and no custom save(); managers are only available if marked use_in_migrations = True.
  • Give a reverse function, or RunPython.noop when reversing needs no data change, so migrate school 0004 still works.
  • Large tables: process in batches with iterator() and bulk_update(), or use update() with expressions. One huge transaction can lock the table and fill logs.
  • Signals do not fire for historical models in a useful way; do the work explicitly.
  • On PostgreSQL, schema and data changes can share a transaction. Still, splitting "add nullable column", "fill data" and "make non-null" into separate migrations makes deploys safer.
  • RunSQL exists for raw SQL, with reverse_sql.

Test data migrations against a copy of production data before deploying.

python
import os
import sys
import tempfile
from pathlib import Path

root = Path(tempfile.mkdtemp())
app = root / "school"
(app / "migrations").mkdir(parents=True)
(app / "__init__.py").write_text("")
(app / "migrations" / "__init__.py").write_text("")
(app / "models.py").write_text(
    "from django.db import models\n\n"
    "class Student(models.Model):\n"
    "    first_name = models.CharField(max_length=30)\n"
    "    last_name = models.CharField(max_length=30)\n"
    "    full_name = models.CharField(max_length=61, blank=True, default='')\n"
)
(app / "migrations" / "0001_initial.py").write_text("""
from django.db import migrations, models

class Migration(migrations.Migration):
    initial = True
    dependencies = []
    operations = [
        migrations.CreateModel(name="Student", fields=[
            ("id", models.BigAutoField(primary_key=True, serialize=False)),
            ("first_name", models.CharField(max_length=30)),
            ("last_name", models.CharField(max_length=30)),
        ]),
        migrations.RunPython(
            lambda apps, se: apps.get_model("school", "Student").objects.bulk_create([
                apps.get_model("school", "Student")(first_name="Isha", last_name="Verma"),
                apps.get_model("school", "Student")(first_name="Omar", last_name="Khan"),
            ]),
            migrations.RunPython.noop,
        ),
    ]
""")
(app / "migrations" / "0002_student_full_name.py").write_text("""
from django.db import migrations, models

class Migration(migrations.Migration):
    dependencies = [("school", "0001_initial")]
    operations = [migrations.AddField("student", "full_name",
                  models.CharField(max_length=61, blank=True, default=""))]
""")
(app / "migrations" / "0003_fill_full_name.py").write_text("""
from django.db import migrations

def forwards(apps, schema_editor):
    Student = apps.get_model("school", "Student")
    batch = []
    for s in Student.objects.filter(full_name="").iterator(chunk_size=500):
        s.full_name = f"{s.first_name} {s.last_name}".strip()
        batch.append(s)
    Student.objects.bulk_update(batch, ["full_name"], batch_size=500)

def backwards(apps, schema_editor):
    apps.get_model("school", "Student").objects.update(full_name="")

class Migration(migrations.Migration):
    dependencies = [("school", "0002_student_full_name")]
    operations = [migrations.RunPython(forwards, backwards)]
""")
sys.path.insert(0, str(root))

import django
from django.conf import settings

settings.configure(
    INSTALLED_APPS=["school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.core.management import call_command
from school.models import Student

call_command("migrate", "school", verbosity=0)
print(list(Student.objects.order_by("id").values_list("full_name", flat=True)))
call_command("migrate", "school", "0002", verbosity=0)
print(list(Student.objects.order_by("id").values_list("full_name", flat=True)))

Standalone script. It writes a small app with three migrations (create, add field, data migration) to a temporary folder, migrates forward, then rolls back to 0002 to show the reverse function. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Isha Verma', 'Omar Khan'] ['', '']

Key points

  • Create with makemigrations --empty, add RunPython
  • Always use apps.get_model() for historical models
  • Provide a reverse function or RunPython.noop
  • Batch large updates
  • Split add column, fill, and constrain into separate steps

Common mistakes

  • Importing the current model class inside a migration
  • Leaving out a reverse function so the migration cannot be rolled back
  • Updating millions of rows in one transaction and locking the table
  • Calling custom model methods that do not exist on historical models

Follow-ups

  • Why does apps.get_model() exist?
  • How would you backfill a column on a 50-million-row table without downtime?
  • What does RunPython.noop do?

Tips

  • Explain historical models clearly, it is the main trap
  • Mention batching and reversibility
  • Tie data migrations to the safe add-fill-constrain sequence