← Back to all tutorials

Migrations

Turn your model definitions into actual database tables — create and apply migrations to keep your database schema in sync with your code.

Migrations

Models define the database structure in Python, but the actual database tables do not exist yet. Migrations are Django's way of propagating model changes into the database schema.

The Two-Step Process

# Step 1: Create migration files
python manage.py makemigrations

# Step 2: Apply them to the database
python manage.py migrate

What makemigrations Does

$ python manage.py makemigrations

Migrations for 'articles':
  articles/migrations/0001_initial.py
    - Create model Article

makemigrations detects changes in your models and creates migration files — Python files that describe what changes to make to the database.

What migrate Does

$ python manage.py migrate

Operations to perform:
  Apply all migrations: admin, articles, auth, ...
Running migrations:
  Applying articles.0001_initial... OK

migrate reads the migration files and executes the SQL to create or alter database tables.

The Migration Workflow

1. Edit models.py (add field, new model, etc.)
2. Run makemigrations → creates a migration file
3. Run migrate → applies changes to the database

Repeat whenever you change models.

Viewing the SQL

# See the exact SQL a migration will run:
python manage.py sqlmigrate articles 0001

Key Takeaways

  • makemigrations creates migration files from model changes
  • migrate applies those changes to the database
  • Always run both commands after changing models
  • Migration files are version-controlled — they track the history of schema changes