Migrations

Migrations turn model changes into database schema changes.

Syntaxpython manage.py makemigrations && python manage.py migrate

Whenever you add or change a model, you create a migration and apply it. This keeps your database schema in sync with your models — and version-controlled.

  1. makemigrations — writes migration files describing the change.
  2. migrate — applies those files to the database.
A Python model class becomes a migration file, which migrate applies to create the matching database tablemodels.pyclass Post(Model)Migration file0001_initial.pyDatabase tableblog_postmakemigrationsmigrate
From Python class to real database table in two commands.

Example

Example · bash
# After editing models.py:
python manage.py makemigrations

# Apply the changes to the database:
python manage.py migrate

# See the SQL a migration would run:
python manage.py sqlmigrate blog 0001

When to use it

  • A developer runs makemigrations after adding a new field to the Product model so Django tracks the schema change.
  • A team applies all pending migrations on a staging server before deploying new code to production.
  • A developer uses showmigrations to verify which migrations have been applied to the current database.

More examples

Create and apply migrations

Generates a migration file for the blog app then applies all pending migrations to the database.

Example · bash
python manage.py makemigrations blog
python manage.py migrate

Inspect migration SQL

Prints the SQL statements for a migration without running them, useful for review and debugging.

Example · bash
python manage.py sqlmigrate blog 0001_initial
# Outputs the raw SQL Django will execute for this migration

Roll back a migration

Reverts the database to a previous migration state, useful during development to undo schema changes.

Example · bash
# Roll back to migration 0002
python manage.py migrate blog 0002

# Roll back all migrations for an app
python manage.py migrate blog zero

Discussion

  • Be the first to comment on this lesson.