Chapter 7 · 10 min read
Models and Migrations
Models and Migrations
A website without data is a brochure. Django stores data in a database, and you describe that data with models. In this chapter you will create the Post model for the blog and learn how migrations carry model changes into the database.
What you will learn
- What a model is and how it maps to a table.
- How to choose field types and options.
- How to relate two models with a
ForeignKey. - The two-step migration workflow:
makemigrationsandmigrate.
From class to table
A model is a Python class that inherits from django.db.models.Model. Each class attribute that is a field becomes a column. Django creates a table named after the app and the class, for example blog_post, and adds an automatic primary key column called id. Django 6.0 changed the default type of this key to a 64-bit integer (BigAutoField), so you do not need to configure anything.
Django uses SQLite by default. It needs no installation, and stores everything in the file db.sqlite3. Later you can switch to PostgreSQL by changing one setting.
Common field types
| Field | Stores | Notes |
|---|---|---|
CharField(max_length=200) | Short text | max_length is required |
TextField() | Long text | No length limit |
IntegerField() | Whole numbers | |
BooleanField(default=True) | True or False | |
DateTimeField(auto_now_add=True) | Date and time | auto_now_add sets it once at creation; auto_now updates it on each save |
ForeignKey(...) | Link to another row | Many-to-one relationship |
EmailField(), URLField(), SlugField() | Validated text |
Useful options: null=True allows a database NULL, blank=True allows an empty value in forms, default= sets a default, unique=True forbids duplicates.
The Post model
Replace blog/models.py:
from django.conf import settings
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name="posts",
)
published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("blog:detail", kwargs={"pk": self.pk})
Walkthrough:
settings.AUTH_USER_MODELrefers to the project's user model without importing it. Using it is the recommended way to point at users.on_delete=models.CASCADEis required on aForeignKey. It means: when a user is deleted, delete their posts too. Other choices includePROTECT(refuse to delete) andSET_NULL. Django 6.1 added database-level variants:DB_CASCADE,DB_SET_NULLandDB_SET_DEFAULT, which let the database do the work instead of Python.related_name="posts"lets you writeuser.posts.all()to get a user's posts.class Metaholds options.ordering = ["-created"]sorts newest first by default; the minus sign means descending.__str__controls how an object prints, in the shell and in the admin.get_absolute_urlreturns the address of one post. It refers to a URL namedblog:detailthat you create later, so do not call it before then.
Migrations: version control for your database
Changing a model does not change the database by itself. You do two steps:
makemigrationscompares your models with the earlier migrations and writes a new migration file describing the difference.migrateapplies unapplied migrations to the database.
python manage.py makemigrations blog
python manage.py migrate
The first command prints Create model Post and creates blog/migrations/0001_initial.py. The second prints Applying blog.0001_initial... OK. Commit migration files to Git: they are part of your code.
To see the SQL that Django will run, use:
python manage.py sqlmigrate blog 0001
To list applied and unapplied migrations:
python manage.py showmigrations
Changing a model later
Suppose you add a field updated:
updated = models.DateTimeField(auto_now=True)
Run makemigrations again. Django creates 0002_...py. If you add a required field to a table that already has rows, Django asks for a default value for the existing rows; give it one, or make the field nullable. Then run migrate.
Check it works
makemigrationsprintsCreate model Post.migrateprintsApplying blog.0001_initial... OK.python manage.py showmigrations blogshows[X] 0001_initial.
Exercises with solutions
Exercise 1: add an updated timestamp
Add an updated field and migrate.
Solution. Add updated = models.DateTimeField(auto_now=True) to Post. Because auto_now fills the value automatically, Django does not ask you for a default. Then run:
python manage.py makemigrations blog
python manage.py migrate
makemigrations prints Add field updated to post. Open 0002_post_updated.py to see the AddField operation Django wrote.
Exercise 2: a unique slug
Add a slug field that must be unique. Why can this be tricky?
Solution. slug = models.SlugField(unique=True, null=True, blank=True). A unique column cannot be added with one fixed default to a table that already has several rows, because every row would get the same value and break the uniqueness rule. Allowing null=True for existing rows, then filling real values, is the usual safe path.
Exercise 3: read the SQL
Print the SQL for migration 0001.
Solution. Run python manage.py sqlmigrate blog 0001. You should see a CREATE TABLE "blog_post" statement with columns id, title, body, published, created and author_id, plus an index on author_id.
Common mistakes
- Changing a model but forgetting
makemigrationsandmigrate. Symptom:no such columnerrors. - Editing a migration that was already applied. Create a new migration instead.
- Adding a required field to a table with rows and not supplying a default.
- Deleting
db.sqlite3to "fix" problems. Acceptable for a throwaway development database, but you lose all data. - Forgetting
on_deleteon aForeignKey. It is required. - Calling
makemigrationswithout the app registered inINSTALLED_APPS. Django reportsNo changes detected.
Key takeaways
- A model class becomes a table; fields become columns.
ForeignKeylinks rows and needson_delete.- The workflow is always
makemigrationsthenmigrate. - Migration files are code: commit them and never edit applied ones.
