Django migrations: safely apply model changes to a database
A Django migration records a model change as an ordered Python file and applies its operations to the database schema. After editing a model, create a draft with `makemigrations`, review it, then apply it with `migrate`. Keep migration files in version control with the code; determine order from dependencies and inspect the generated SQL instead of relying on filename numbers alone.
Django migrations: safely apply model changes to a database
A Django migration records a model change as an ordered Python file and applies its operations to the database schema. After editing a model, create a draft with makemigrations, review it, then apply it with migrate. Keep migration files in version control with the code; determine order from dependencies and inspect the generated SQL instead of relying on filename numbers alone.
This guide covers the usual relational-database workflow described in the Django 6.0 documentation (checked 2026-11-23). Details can vary by Django version and database backend. Commands and code are illustrative and were not run in a project.
What does a migration file record?
makemigrations compares current models with the model state represented by the latest migration and writes the difference to a file. The file contains declarative operations such as AddField, CreateModel, and AlterField, plus dependencies on other migrations. Django builds an execution graph from these dependencies; it does not decide order from the numeric part of filenames. Dependencies also express cross-app requirements such as a foreign key whose table must exist first. Django 6.0: migrations
accounts.0005 ──────┐
├──> orders.0003
orders.0002 ────────┘For example, orders.0003 runs after both accounts.0005 and orders.0002 if it depends on both. This graph lets migrations from parallel branches coexist even if their filename numbers match, though the changes may still conflict semantically.
Create and apply a model change
Suppose you add an optional display name to Customer:
class Customer(models.Model):
email = models.EmailField(unique=True)
display_name = models.CharField(max_length=120, null=True, blank=True)Activate the project’s virtual environment and confirm its settings point to the intended database. Then create a named migration for the app:
python manage.py makemigrations customers --name add_customer_display_nameCheck the output and open the new file under customers/migrations/. Autodetection compares models with the state stored in migration files; it does not fully understand your data or whether the proposed operation matches your intent. A rename may be represented as adding one field and deleting another, which can lose existing values. Review whether the operation preserves data and edit the migration when needed. Django 6.0: migrations Command reference
Before applying, inspect the plan, backend-specific SQL, and recorded status:
python manage.py showmigrations customers --plan
python manage.py sqlmigrate customers 0002
python manage.py showmigrations customersshowmigrations --plan displays the pending operations and dependency order; the default listing marks applied migrations with [X]. sqlmigrate prints the statements for a migration. It connects to a database to resolve constraint names, so inspect SQL against a copy compatible with the database where you plan to apply it. 0002 is a placeholder: use the actual migration name. Command reference
After review in development, apply the migrations:
python manage.py migrate
python manage.py showmigrations customersWith no arguments, migrate applies all unapplied migrations in dependency order. Naming an app can still apply migrations from other apps when dependencies require them. Confirm the expected [X] status afterward. Commit the model change and migration together so teammates and deployment environments receive the same history. In production, run the reviewed, version-controlled migration through the deployment process and verify the resulting state. Django 6.0: migrations Command reference
How are data migrations different?
A schema migration changes tables, columns, indexes, or constraints. A data migration changes existing rows, for example by filling values or moving data. Combining a large data rewrite with a structural change can make lock time and data-loss risk harder to assess. For a new required field on a populated table, a safer staged approach may be to add a nullable field, fill values in a separate step, then enforce the constraint. The right sequence depends on the database, data size, and write traffic and should be validated for that system. Django 6.0: writing migrations
When moving data with RunPython, use the model version from the migration state rather than importing the current model from models.py:
from django.db import migrations
def fill_display_name(apps, schema_editor):
Customer = apps.get_model("customers", "Customer")
for customer in Customer.objects.filter(display_name__isnull=True).iterator():
customer.display_name = customer.email.split("@", 1)[0]
customer.save(update_fields=["display_name"])
class Migration(migrations.Migration):
dependencies = [("customers", "0002_add_customer_display_name")]
operations = [migrations.RunPython(fill_display_name, migrations.RunPython.noop)]This is a hypothetical rule, not a claim that an email prefix is a suitable name; the code was not run. Historical models expose the fields and relationships as they existed at that point. Importing a current model can make an old migration fail when a fresh database replays the history. A reverse function of noop does not restore changed data; if rollback matters, define a genuinely safe reverse operation or document the migration as irreversible. Writing migrations Historical models
Resolve branch conflicts with a merge migration
If two branches create different migrations from the same starting point, their files can share a number. Django uses migration names and dependencies, not numbers alone, so that is not necessarily an error. If both branch tips remain, however, the graph has multiple heads. Review each operation and dependency first to decide whether both changes can be applied.
When appropriate, makemigrations --merge can create an empty migration that joins the heads:
python manage.py makemigrations --merge customersThe merge node connects histories; it does not combine the operations or resolve a business-level conflict for you. Review the changes and their order against a development database. Incorrect dependency edits can leave an inconsistent history, such as a migration applied while one of its prerequisites is missing, and Django will refuse to proceed. Django 6.0: history consistency
Existing databases and reversals
If tables already exist before migrations are introduced, migrate --fake-initial may help mark the initial migration as applied, but it is not a general safety check. Django checks whether the tables or columns named by the initial operations exist; it does not verify that the full schema, constraints, and types match. Confirm independently that the database matches the initial migration and has not been manually altered. --fake goes further by changing migration state without executing SQL; it is an advanced operation that can leave the recorded history inconsistent with the real schema. Existing tables and initial migrations migrate options
Reversing is not always a simple undo. migrate app_label migration_name moves the app to a target point, and moving backward can also unapply dependent migrations from other apps. Inspect --plan first and look for destructive or irreversible operations. Some operations have no reverse behavior and raise IrreversibleError. Keep backups and a recovery plan; do not assume one command can restore every data change. Reversing migrations migrate command
Database-backend differences
Backends with DDL transactions, including PostgreSQL and SQLite, run migration operations in one transaction by default. MySQL and Oracle do not provide the same transaction behavior for schema changes, so a failed migration may require manual cleanup. MySQL operations can still involve locks or interruptions. SQLite emulates some schema changes by creating a new table, copying rows, and replacing the old table; that can be slow for large tables. Check the limits of the Django version and database engine actually used by the project. Django 6.0: backend support and transactions
Before applying a migration
Prepare the model and migration in the same code change. Read the generated operations and dependency graph, inspect the plan with showmigrations --plan, and review SQL with sqlmigrate against a compatible database copy. Validate behavior in development or staging with representative data. Before production, plan for backups, locks and runtime, acceptable write interruption, and recovery if application fails. Verify status after application. Once a migration has been shared or applied, add a new migration for later changes instead of rewriting history.