Skip to content
devtoolbox.cc

Django · Chapter 4 of 8

Django models and migrations: fields, choices, admin

12 min study · Examples checked with Django 6.1 on Python 3.14 ·

Until now the lessons lived in a dictionary in views.py. This chapter moves them into the database. In Django, each table is described by a model, a Python class whose attributes are the columns. From the model Django creates the table, validates values, builds forms and admin pages, and lets you query with Python instead of SQL. Changes to models reach the database through migrations, small versioned scripts that Django writes for you.

The database setting

New projects use SQLite, configured in settings.py under DATABASES with the file db.sqlite3 in the project folder. That’s enough for development and small sites. For production with many simultaneous writers, PostgreSQL is the usual choice: install a driver (psycopg), change ENGINE to django.db.backends.postgresql, and give the name, user, host and password, the password read from an environment variable. Models and queries stay the same.

A Lesson model

Replace catalog/models.py:

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.urls import reverse


class Lesson(models.Model):
    class Level(models.TextChoices):
        BEGINNER = "beginner", "Beginner"
        ADVANCED = "advanced", "Advanced"

    title = models.CharField(max_length=120, unique=True)
    minutes = models.PositiveSmallIntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(180)]
    )
    level = models.CharField(max_length=20, choices=Level, default=Level.BEGINNER)
    summary = models.TextField(blank=True)
    published = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["title"]
        constraints = [
            models.CheckConstraint(
                condition=models.Q(minutes__gte=1, minutes__lte=180),
                name="lesson_minutes_1_180",
            ),
        ]

    def __str__(self) -> str:
        return self.title

    def get_absolute_url(self) -> str:
        return reverse("catalog:lesson", args=[self.pk])

Each attribute is a field: CharField for short text with a required max_length, TextField for long text, PositiveSmallIntegerField for small whole numbers, BooleanField, DateTimeField. Django adds an auto-incrementing id primary key unless you define one. unique=True creates a unique index, default fills in values not given, and auto_now_add=True stores the creation time once.

Level is a TextChoices enumeration. The first value of each member is stored in the database, the second is the human label, and choices=Level limits the field to those values in forms, validation and the admin. lesson.get_level_display() returns the label, "Advanced". Meta.ordering sets the default sort order for queries, and __str__ decides how a lesson appears in the shell, the admin and templates. get_absolute_url is the conventional method that returns an object’s page URL; templates and the admin use it for “view on site” links.

Create the table with migrations

python manage.py makemigrations catalog
python manage.py migrate

makemigrations compares your models with the existing migrations and writes a new file, here catalog/migrations/0001_initial.py. migrate applies every migration the database hasn’t seen. To see the SQL a migration will run, use sqlmigrate:

CREATE TABLE "catalog_lesson" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  "title" varchar(120) NOT NULL UNIQUE, "minutes" smallint unsigned NOT NULL CHECK ("minutes" >= 0),
  "level" varchar(20) NOT NULL, "summary" text NOT NULL, "published" bool NOT NULL,
  "created_at" datetime NOT NULL,
  CONSTRAINT "lesson_minutes_1_180" CHECK (("minutes" >= 1 AND "minutes" <= 180)));

Migration files are part of your code: commit them, review them, and never edit one that has already been applied somewhere. Every model change, such as a new field, a renamed field or a changed max_length, goes through the same two commands, and Django asks how to fill existing rows when a new required field has no default. showmigrations lists which migrations have run.

Validation: validators, choices and constraints

Django checks values at two levels. Validators, choices and max_length run when a form validates or when you call full_clean(); they produce friendly messages. Database constraints run on every insert and update, whatever code does it:

Lesson(title="Loops", minutes=500, level="expert").full_clean()
ValidationError {'minutes': ['Ensure this value is less than or equal to 180.'],
                 'level': ["Value 'expert' is not a valid choice."]}

Lesson.objects.create(title="Loops", minutes=500)
IntegrityError: CHECK constraint failed: lesson_minutes_1_180

Lesson.objects.create(title="Variables", minutes=5)      (a second "Variables")
IntegrityError: UNIQUE constraint failed: catalog_lesson.title

The important detail: save() and objects.create() do not run validators or check choices. Forms call full_clean() for you (chapter 7), but code that creates objects directly does not, which is why rules that must always hold also belong in the database as unique or a CheckConstraint. The validators give users good error messages, and the constraints guarantee the data.

null versus blank

Two options sound alike and are not. null=True is about the database: the column may store NULL. blank=True is about validation: forms may leave the field empty. For text fields, Django’s convention is blank=True without null=True, so “no summary” is always stored as an empty string and there aren’t two kinds of empty. For numbers, dates and foreign keys, which have no empty-string form, optional fields need both. A BooleanField with null=True gives a third state, “unknown”, when you need it.

The admin site

Django generates a management interface for registered models. Replace catalog/admin.py:

from django.contrib import admin

from .models import Lesson


@admin.register(Lesson)
class LessonAdmin(admin.ModelAdmin):
    list_display = ["title", "level", "minutes", "published"]
    list_filter = ["level", "published"]
    search_fields = ["title", "summary"]

Create an account with python manage.py createsuperuser, run the server and open /admin/. You can add, edit, search and filter lessons, with all field validation applied. The admin is meant for trusted staff, not for the public, and it is often the fastest way to enter test data while the rest of the site is being built.

Practice

Add an optional video_url field (URLField(blank=True)) and a difficulty number from 1 to 5 that existing lessons get as 1. Create and apply the migration, check its SQL with sqlmigrate, and add difficulty to the admin’s list_display.

Answer check: difficulty = models.PositiveSmallIntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]), and add a matching CheckConstraint if the database should enforce it. makemigrations writes 0002_...; the default fills existing rows, so Django asks no questions. URLField is a varchar column, and the URL check happens only in full_clean() and forms.

Summary

A model class describes a table: fields with types, options such as unique and default, TextChoices for fixed values, and Meta for ordering and constraints. makemigrations records changes, migrate applies them, and the files are committed. full_clean() and forms run validators, while save() relies on database constraints. Use blank for optional form input, null only where a type has no empty value, and register models in the admin.

All Django chapters