Migrations
Migrations turn model changes into database schema changes.
Syntax
python manage.py makemigrations && python manage.py migrateWhenever 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.
makemigrations— writes migration files describing the change.migrate— applies those files to the database.
Example
# 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 0001When 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.
python manage.py makemigrations blog
python manage.py migrateInspect migration SQL
Prints the SQL statements for a migration without running them, useful for review and debugging.
python manage.py sqlmigrate blog 0001_initial
# Outputs the raw SQL Django will execute for this migrationRoll back a migration
Reverts the database to a previous migration state, useful during development to undo schema changes.
# 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