Full answer
During a rolling deploy, old and new versions of the code run at the same time against one database. A migration is safe only if both versions work with the schema before and after it. Locks are the other danger: some ALTER TABLE statements take an exclusive lock, and on a busy 50-million-row table even a short wait queues every other query behind it.
Patterns for common changes:
Adding a column
- Add it nullable, or with
db_default(Django 5.0+) so the database supplies the value. On PostgreSQL 11+, adding a column with a constant default is a metadata-only change and fast. A Python-sidedefault=alone is applied by Django during the migration and then dropped from the database, which is not the same thing. - Deploy code that writes the new column.
- Backfill old rows in batches (a data migration or a management command with small transactions).
- In a later release, make it
NOT NULLor add constraints. On PostgreSQL, add aCHECKconstraint asNOT VALIDand validate it separately to avoid a long lock.
Adding an index
- Use
AddIndexConcurrentlyfromdjango.contrib.postgres.operationsin a migration withatomic = False. It does not block writes.
Renaming or removing a column
- Never rename in one step. Add the new column, write both, backfill, switch reads, stop writing the old one, then drop it later.
- To drop a field: first remove it from the model but keep it in the database using
SeparateDatabaseAndState(or make it nullable so old code inserts still work), deploy, then drop the column in a later release.
Process habits
python manage.py sqlmigrate app 0042to read the SQL before release.- Set
lock_timeout(andstatement_timeout) for the migration session so it fails fast instead of queuing traffic. - Run migrations once, as a separate release step, not in every container's start command.
- Tools such as
django-pg-zero-downtime-migrationsor linters likedjango-migration-lintercatch unsafe operations in CI.
import os
import sys
import types
import django
from django.conf import settings
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
# Needs a running PostgreSQL server; connection details come from the usual PG* variables
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": os.environ.get("PGDATABASE", "school"),
"USER": os.environ.get("PGUSER", "postgres"),
"PASSWORD": os.environ.get("PGPASSWORD", ""),
"HOST": os.environ.get("PGHOST", "localhost"),
"PORT": os.environ.get("PGPORT", "5432"),
}},
)
django.setup()
from django.contrib.postgres.operations import AddIndexConcurrently
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
from django.db.models.functions import Now
def sql_for(operations, state, atomic=True):
"""Return the SQL Django would run for these operations (like sqlmigrate)."""
with connection.schema_editor(collect_sql=True, atomic=atomic) as editor:
for op in operations:
new_state = state.clone()
op.state_forwards("school", new_state)
op.database_forwards("school", editor, state, new_state)
state = new_state
return [s for s in editor.collected_sql if not s.startswith("--")], state
state = ProjectState()
create = [migrations.CreateModel("Attendance", [
("id", models.BigAutoField(primary_key=True)),
("roll_no", models.IntegerField()),
])]
_, state = sql_for(create, state)
step1 = [migrations.AddField("attendance", "source",
models.CharField(max_length=10, db_default="manual"))]
sql, state = sql_for(step1, state)
print("Step 1, add column with a database default:")
print(" ", sql[0])
step2 = [AddIndexConcurrently("attendance",
models.Index(fields=["source"], name="att_source_idx"))]
sql, state = sql_for(step2, state, atomic=False)
print("Step 2, index without blocking writes:")
print(" ", sql[0])
remove = [migrations.SeparateDatabaseAndState(
state_operations=[migrations.RemoveField("attendance", "source")],
database_operations=[],
)]
sql, state = sql_for(remove, state)
print("Step 3, remove from Django state only, SQL statements:", len(sql))
Standalone script that needs PostgreSQL and `pip install "psycopg[binary]"`. Set PGHOST, PGPORT, PGUSER, PGPASSWORD and PGDATABASE to point at a scratch database before running it. It prints the SQL Django generates for each step, the same way sqlmigrate does, without applying it. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): Step 1, add column with a database default: ALTER TABLE "school_attendance" ADD COLUMN "source" varchar(10) DEFAULT 'manual' NOT NULL; Step 2, index without blocking writes: CREATE INDEX CONCURRENTLY "att_source_idx" ON "school_attendance" ("source"); Step 3, remove from Django state only, SQL statements: 0
Key points
- Old and new code must both work with the schema during deploys
- Add nullable or db_default columns, backfill, then constrain
- AddIndexConcurrently with atomic = False on PostgreSQL
- Remove fields in two releases with SeparateDatabaseAndState
- Read sqlmigrate output and set lock_timeout
Common mistakes
- Adding a NOT NULL column without a database default to a huge table in one step
- Renaming a column while old code still reads the old name
- Creating indexes without CONCURRENTLY on a busy PostgreSQL table
- Running migrate from every container at startup
Follow-ups
- How would you rename a heavily used column with no downtime?
- Why must a migration using AddIndexConcurrently set atomic = False?
- What is the difference between default= and db_default= during a migration?
Tips
- Start from the rolling-deploy constraint: two code versions, one schema
- Give the add, backfill, constrain sequence
- Mention lock_timeout and reading sqlmigrate output