Skip to the workspace
Pebellslearn by building
Models, Views, Admin and Tests  ›  Lesson

models.py and Migrations

models.py 16 minA model class in models.py describes a database table in Python, and migrations are the recorded steps, made by makemigrations and applied by migrate, that bring the real database in line with it.

django / models.py and Migrations

Explore each scene at your own pace.

01 · The rule

The rule

models.py and Migrations

The cookbook needs somewhere to keep its recipes. You could write CREATE TABLE by hand, then keep the SQL, the Python and every teammate's database in sync forever. Django lets you describe the table once, in Python, and generates the database changes for you, in recorded steps anyone can replay.

The rule

Describe in models.py; makemigrations writes the plan; migrate builds it.

A model is a class that becomes a table. Each field becomes a column:

# recipes/models.py
from django.db import models

class Recipe(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    minutes = models.PositiveIntegerField()
    instructions = models.TextField(blank=True)
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

What you get:

  • A table named recipes_recipe (app name, underscore, model name in lower case).
  • An automatic id primary key; you did not write it.
  • Rules in the fields: CharField must have max_length; unique=True forbids two recipes with the same slug; blank=True lets forms leave instructions empty; auto_now_add=True stamps the creation time.
  • __str__ gives each recipe a readable name in the shell and the admin.

Writing the class changes nothing in the database yet. Two commands do that:

python manage.py makemigrations   # writes recipes/migrations/0001_initial.py
python manage.py migrate          # applies it: the table now exists

A migration is a small Python file listing operations such as "create model Recipe" or "add field servings". Migrations are numbered and chained, and Django records which ones each database has applied, so migrate only runs the new ones. Curious what SQL it will run? python manage.py sqlmigrate recipes 0001 prints it.

Migration files are part of your code: commit them. Teammates and servers run migrate and get exactly the same tables.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.