Django Migrations
Your models describe what the database should look like. Migrations are how Django gets the real database there. Each migration is a small Python file that records one set of schema changes — create a table, add a column, rename a field — so the changes can be applied in order on your laptop, your teammate's laptop and the production server.
The two commands
| Command | What it does |
|---|---|
python manage.py makemigrations |
compares your models with the existing migration files and writes new migration files |
python manage.py migrate |
applies unapplied migrations to the database |
python manage.py showmigrations |
lists migrations and whether they're applied ([X]) |
python manage.py sqlmigrate app 0001 |
prints the SQL a migration would run |
python manage.py migrate app 0001 |
migrates forward or back to a specific migration |
The workflow is always: change models → makemigrations → review → migrate → commit the migration file.
Creating the first migration
With a fresh Book model in the books app:
python manage.py makemigrations booksMigrations for 'books':
books/migrations/0001_initial.py
+ Create model Book
The generated file is plain Python you can read (and commit to version control):
# books/migrations/0001_initial.py
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Book",
fields=[
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
("title", models.CharField(max_length=200)),
("pages", models.PositiveIntegerField(default=0)),
],
),
]Apply it and inspect the result:
python manage.py migrate books
python manage.py showmigrations booksOperations to perform:
Apply all migrations: books
Running migrations:
Applying books.0001_initial... OK
books
[X] 0001_initial
Django records applied migrations in a table called django_migrations, so migrate never runs the same one twice.
Changing a model
Add a field, then run makemigrations again. Django detects the difference and writes 0002:
class Book(models.Model):
title = models.CharField(max_length=200)
pages = models.PositiveIntegerField(default=0)
isbn = models.CharField(max_length=13, blank=True, default="") # newpython manage.py makemigrations books
python manage.py sqlmigrate books 0002Migrations for 'books':
books/migrations/0002_book_isbn.py
+ Add field isbn to book
BEGIN;
--
-- Add field isbn to book
--
ALTER TABLE "books_book" ADD COLUMN "isbn" varchar(13) DEFAULT '' NOT NULL;
ALTER TABLE "books_book" ALTER COLUMN "isbn" DROP DEFAULT;
COMMIT;
(The sqlmigrate output above is for PostgreSQL; each database backend generates its own SQL.)
Tip: When you add a non-nullable field to a table that already has rows, Django needs a value for those rows. Give the field a
default, make itnull=True, or answer the interactive promptmakemigrationsshows you.
Under the hood: the schema editor
Migration operations don't write SQL themselves — they call the database's schema editor, which knows each backend's dialect. Playground examples use the schema editor directly because they have no migrations folder. With collect_sql=True you can see the SQL it would run for SQLite:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Book(models.Model):
title = models.CharField(max_length=200)
pages = models.PositiveIntegerField(default=0)
class Meta:
app_label = "demo"
with connection.schema_editor(collect_sql=True) as editor:
editor.create_model(Book)
print("\n".join(editor.collected_sql))CREATE TABLE "demo_book" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(200) NOT NULL, "pages" integer unsigned NOT NULL CHECK ("pages" >= 0));
Adding a column to a table with data
This is what migration 0002 does when it runs AddField: alter the existing table and keep the rows. We create the table, insert a row, then add a field:
import django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
class Book(models.Model):
title = models.CharField(max_length=200)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Book)
Book.objects.create(title="Dune")
def columns():
with connection.cursor() as cursor:
return [c.name for c in connection.introspection.get_table_description(cursor, "demo_book")]
print("before:", columns())
isbn = models.CharField(max_length=13, default="unknown")
isbn.set_attributes_from_name("isbn")
with connection.schema_editor() as editor:
editor.add_field(Book, isbn)
print("after: ", columns())
with connection.cursor() as cursor:
cursor.execute("SELECT id, title, isbn FROM demo_book")
print(cursor.fetchall())before: ['id', 'title']
after: ['id', 'title', 'isbn']
[(1, 'Dune', 'unknown')]
The existing row received the field's default — exactly what happens when you migrate a production database.
Data migrations
Not every migration changes the schema. A data migration uses RunPython to transform rows, for example filling a new slug field from existing titles:
from django.db import migrations
from django.utils.text import slugify
def fill_slugs(apps, schema_editor):
Book = apps.get_model("books", "Book") # historical model, not a direct import
for book in Book.objects.all():
book.slug = slugify(book.title)
book.save(update_fields=["slug"])
class Migration(migrations.Migration):
dependencies = [("books", "0003_book_slug")]
operations = [migrations.RunPython(fill_slugs, migrations.RunPython.noop)]Create an empty file to edit with python manage.py makemigrations books --empty --name fill_slugs.
Note: Never edit a migration that has already been applied on another machine. Write a new migration instead.
Test yourself
Which command writes new migration files after you change a model?
- migrate
- makemigrations
- sqlmigrate
- runserver
How does Django know which migrations have already run?
- It checks file timestamps
- It records them in the
django_migrationstable - It re-runs all of them every time
- It asks you
In a data migration, how should you access a model?
from books.models import Bookapps.get_model("books", "Book")Book = models.Model- Raw SQL only