Migration (Django)

A Django migration is a versioned file that records a change to your database schema, derived from changes to your models. Migrations let you evolve the database over time in a controlled, repeatable, reversible way.

Django

When you add a field, model, or index, the database does not change until you create and apply a migration. Migrations are Python files in each app's migrations/ folder that describe operations (CreateModel, AddField, etc.), forming an ordered history of your schema.

The workflow is two commands: makemigrations inspects your models, compares them to the last migration, and writes a new migration file; migrate applies any unapplied migrations to the database. Because migrations are files, you commit them so every developer and server applies the same changes.

Migrations can be reversed (migrate appname 0003 to roll back), and Django tracks which are applied in a django_migrations table. For data changes (not just schema), you write data migrations using RunPython.

Syntax

python manage.py makemigrations
python manage.py migrate

Examples

Python

# after editing models.py
# 1) generate the migration file
python manage.py makemigrations blog

# 2) apply it to the database
python manage.py migrate

# roll back to an earlier migration
python manage.py migrate blog 0002

Learn it in a lesson

See also

Back to the Dictionary