1 · Structure and rendering · 30 MIN
Django models and database constraints
Database constraints protect invariants across application processes.
A model defines persistent fields and indexes. A unique slug is enforced by the database, so two concurrent writers cannot both create the same value successfully. Create migration files and apply them before querying a new schema. QuerySets are lazy: constructing one does not immediately fetch its rows. Restricting selected fields and page size prevents accidentally loading an entire large table. The model stores public course metadata; user progress should use a separate relation with an ownership key.
Apply migrations to a disposable development database.
Read the example
# courses/models.py
from django.db import models
class Course(models.Model):
slug = models.SlugField(unique=True)
title = models.CharField(max_length=160)
published = models.BooleanField(default=False, db_index=True)
class Meta:
ordering = ["id"]
# Run: python manage.py makemigrations courses
# Then: python manage.py migrate
# In python manage.py shell:
# Course.objects.create(slug="react", title="React foundations", published=True)
# list(Course.objects.filter(published=True).values("slug", "title")[:20])Check the expected output
After migration and insertion, the query returns the published React course. A duplicate slug violates the unique constraint.
Your challenge
Add a lesson model related to Course, migrate it and query a course with its ordered lessons without an N+1 loop.
Solution cost: Depends on indexes, selected rows and joins; inspect the query plan. time · O(p) for p materialized page rows. space
Common trap
Calling list on an unbounded QuerySet materializes every matching row.
Study the project implementation
# courses/models.py
from django.db import models
class Course(models.Model):
slug = models.SlugField(unique=True)
title = models.CharField(max_length=160)
published = models.BooleanField(default=False, db_index=True)
class Meta:
ordering = ["id"]
# Run: python manage.py makemigrations courses
# Then: python manage.py migrate
# In python manage.py shell:
# Course.objects.create(slug="react", title="React foundations", published=True)
# list(Course.objects.filter(published=True).values("slug", "title")[:20])Further reading: Official documentation
Next lesson: Django forms, CSRF and server validation →