The Django ORM done well: models, migrations and queries that stay fast and correct
TL;DR
Difficulty: Intermediate
Data reaches your tables through many doors, and in Django only forms and the admin call full_clean(). save(), update(), the bulk methods and Django REST Framework skip it.
- So every rule that would cost money goes into Meta.constraints: the database enforces it everywhere, and since Django 4.1 full_clean() checks it for forms too.
- Money in DecimalField, time zones on, statuses as TextChoices with a CheckConstraint. Django 5.0 adds db_default and GeneratedField.
- QuerySets are lazy. Name them after the page (for_board) so filter and loading travel together.
- A page's query count must not contain n: select_related when a link points at one object, prefetch_related when it points at many. The example board went from 61 queries to 3, pinned by a test at two sizes.
Almost every Django project starts fast and clean, and a year later has a slow list page and a stock count nobody trusts. This chapter works through the Django ORM as of Django 5.0, from fields and constraints to migrations, QuerySets and indexes, on the same bicycle workshop application as the Rails series, and takes its slowest page from 61 queries to 3.
The question behind this chapter
"How do I model data with the Django ORM so that it stays fast and correct as the project grows?" Almost every Django project starts well. The models file is short, the pages are quick, the data is clean. Then a year goes by. A list page takes two seconds, a report shows a part in stock that nobody can find on the shelf, and two customers turn up for the same Saturday slot with the same mechanic. None of that is a framework failure. It is the gap between what the object relational mapper (ORM) does for you and what you assumed it does.
This chapter closes that gap. It works through the Django ORM from the official documentation, as of Django 5.0 (5.0.4 is the current patch release at the time of writing) and Python 3.12, on PostgreSQL1. It covers models and fields, migrations, relationships, constraints and validation, managers and QuerySets, expressions, aggregation, the N+1 problem, bulk operations, transactions and indexes, plus the two additions in Django 5.0 that matter most for data modelling.
The example is the one this whole series uses, and it is invented. Freewheel Cycles runs six bicycle repair workshops in and around Limerick (freewheelcycles.example): 38 mechanics, about 1,150 repair bookings a week, 9,000 active customers, 2,400 spare parts in stock. Its founder Niamh wanted her spreadsheets and a rented booking widget replaced by an application of her own. Her developers Aisling and Cian built a two week spike of the core in both frameworks before choosing. This is the Django version of the spike, with the same schema and the same slow page as the Rails chapter Active Record done well, so you can compare like for like. If you have not set up the project yet, starting a new Django project covers the custom user model, time zones and money fields this chapter builds on, and how a Django project is structured explains the apps used here: workshops, bookings, repairs, parts and accounts, inside the project package freewheel.
The one idea to take away: only the database guards every door
Here is the model I want you to keep, because everything else in this chapter hangs off it.
Data reaches a table through several doors. A form in the browser is one. The Django admin is another. Code that calls save() directly, a management command, a data migration, a Django REST Framework (DRF) serializer, a bulk import, a QuerySet.update() and, later, the small Python service that will forecast parts demand are all doors too. Django checks some of them and leaves others open, and the documentation says exactly which.
- A
ModelForm, and with it the admin, calls the model'sfull_clean()method, which runs field validation, yourclean()method, uniqueness checks and, since Django 4.1, the constraints you declared inMeta.constraints23. - A plain
save()does not. The documentation is blunt:full_clean()"will not be called automatically" when you callsave()2. QuerySet.update(),bulk_create()andbulk_update()do not callsave()at all, so no validation and nopre_saveorpost_savesignals4.- Django REST Framework's
ModelSerializerstopped callingfull_clean()in version 3.0, and it does not call the model'sclean()either5. - Anything outside Django, a database console or another service, sees only what the database itself enforces.
Count the doors in that list and you see the rule: only the database stands at every door. A rule that lives only in Python is a rule that some door ignores. In Rails the default is the other way round, because save runs validations unless you ask it not to6, so Rails developers can forget about doors longer. Django is explicit, and that is fair and consistent with its own design philosophy, but it hands you the job of knowing which door you are using.
My rule of thumb follows from it. If breaking a rule would cost money, a customer or a promise, it goes into Meta.constraints first. Since Django 4.1 the same declaration is also checked by full_clean(), so forms show a friendly error and every other door hits a hard stop in the database. One line, two layers.
Example: the double booked Saturday slot
30% of Freewheel's online bookings arrive between Friday 6pm and Saturday noon. That is about 345 bookings in 18 hours, roughly 19 an hour, and they bunch up on the same popular morning slots. Aisling first wrote the rule "one mechanic, one booking per start time" in the booking form's clean() method: look for an existing booking with this mechanic and start time, and refuse if there is one.
It worked grand in every test. Then two customers pressed "book" for Seán's 9am slot within the same second. Both requests ran the check, both found nothing (neither booking existed yet), both saved. Two customers, one mechanic, one slot. The check and the insert were two separate steps with a gap between them, and a check in Python cannot close that gap.
Here is what closes it, in the Booking model:
# bookings/models.py (extract)
from django.db import models
from django.db.models import Q
class Booking(models.Model):
mechanic = models.ForeignKey(
"workshops.Mechanic", on_delete=models.PROTECT, related_name="bookings"
)
starts_at = models.DateTimeField()
cancelled_at = models.DateTimeField(null=True, blank=True)
# ... the other fields follow later in this chapter
class Meta:
constraints = [
# A cancelled booking frees the slot, so only live bookings count.
models.UniqueConstraint(
fields=["mechanic", "starts_at"],
condition=Q(cancelled_at__isnull=True),
name="one_live_booking_per_mechanic_slot",
),
]
Now the database holds a unique index over mechanic and start time for every booking that is not cancelled. The booking form still calls full_clean(), which checks the constraint with a query and shows a polite message in the normal case. In the rare case where two requests race, the second insert fails with an IntegrityError, the view catches it and offers the next free slot. The customer sees "that slot has just gone", not a double booking on Saturday morning.
What the Django ORM is, and what it borrowed
An ORM maps rows in database tables to objects in your code. You write Booking.objects.filter(mechanic=daniel) and the ORM writes the Structured Query Language (SQL) for you.
Django's design philosophies say plainly that models should encapsulate every aspect of an object, "following Martin Fowler's Active Record design pattern"7. Fowler defined that pattern in Patterns of Enterprise Application Architecture (2002) as an object that wraps a row, encapsulates the database access and adds domain logic on that data8. Rails named its ORM after the same pattern. So the two frameworks start from the same idea, and the differences are in where the truth lives.
- In Rails, you write migrations, the database schema is the truth, and the model reads its columns from the database when the application starts.
- In Django, you write the model class with every field declared, and
makemigrationsworks out the migration from the difference between your models and the migration history. The models file is the truth, and you can read the whole schema in it.
Neither is better in the abstract. Django's way means one file shows you every column, type and constraint. Rails's way means the database never drifts from what the framework thinks, because the framework asks it. The same design philosophies page also says the database layer should "execute SQL statements as few times as possible", which is why save() is explicit and why select_related() exists7. Hold on to that sentence. It comes back in the N+1 section.
Example: the first two models
The workshops app holds the workshops and the mechanics. A mechanic is a login (the custom user model from the previous chapter) attached to one workshop.
# workshops/models.py
from django.conf import settings
from django.db import models
class Workshop(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
def __str__(self):
return self.name
class Mechanic(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
workshop = models.ForeignKey(
Workshop, on_delete=models.PROTECT, related_name="mechanics"
)
display_name = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.display_name
Every field is declared, with its type and its limits. The related_name gives the reverse side a readable name, so workshop.mechanics.all() reads like English. Nothing about this file is magic: you can read it top to bottom and know the table.
The example schema at a glance
Before the details, the whole schema. It is the same as in the Rails chapter, model for model, so the two versions can be compared directly. Identifiers are English in code.
| Model | App | Key fields | Relationships |
|---|---|---|---|
| Workshop | workshops | name, city | has many mechanics, bookings |
| Mechanic | workshops | display_name, is_active | one user, belongs to one workshop |
| Customer | bookings | name, email (unique), phone | has many bikes, bookings |
| Bike | bookings | make, description | belongs to one customer |
| Booking | bookings | starts_at, ends_at, cancelled_at, created_at | workshop, mechanic, customer, bike |
| JobCard | repairs | status, notes | one booking, many parts through PartUsage |
| JobCardPhoto | repairs | kind (before or after), image | belongs to one job card |
| Part | parts | sku (unique), name, price, stock_quantity, reorder_level | many job cards through PartUsage |
| PartUsage | parts | quantity, unit_price, line_total | one job card, one part |
| Invoice | repairs | number (unique), net_amount, vat_rate, vat_amount, issued_at | one job card |
# bookings/models.py
from django.db import models
from django.db.models import F, Q
from django.db.models.functions import Now
class Customer(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=30, blank=True)
class Bike(models.Model):
customer = models.ForeignKey(
Customer, on_delete=models.CASCADE, related_name="bikes"
)
make = models.CharField(max_length=100)
description = models.CharField(max_length=200, blank=True)
class Booking(models.Model):
workshop = models.ForeignKey(
"workshops.Workshop", on_delete=models.PROTECT, related_name="bookings"
)
mechanic = models.ForeignKey(
"workshops.Mechanic", on_delete=models.PROTECT, related_name="bookings"
)
customer = models.ForeignKey(
Customer, on_delete=models.PROTECT, related_name="bookings"
)
bike = models.ForeignKey(Bike, on_delete=models.PROTECT, related_name="bookings")
starts_at = models.DateTimeField()
ends_at = models.DateTimeField()
cancelled_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(db_default=Now()) # new in Django 5.0
class Meta:
constraints = [
models.UniqueConstraint(
fields=["mechanic", "starts_at"],
condition=Q(cancelled_at__isnull=True),
name="one_live_booking_per_mechanic_slot",
),
models.CheckConstraint(
check=Q(ends_at__gt=F("starts_at")),
name="booking_ends_after_it_starts",
),
]
indexes = [
models.Index(fields=["workshop", "starts_at"], name="booking_workshop_start_idx"),
]
The repairs and parts apps follow in the next sections, where each new idea first appears.
Fields that carry money, time and status correctly
A surprising share of data bugs come down to the wrong field type. Three kinds of value deserve care: money, time and status.
Money goes into DecimalField, never FloatField. A float stores some decimals inexactly, and cents drift. DecimalField takes two required arguments: max_digits, the total number of digits, and decimal_places, the digits after the point9. In Python you get a Decimal, which adds up exactly.
Time goes into DateTimeField with time zone support on. Since Django 5.0, USE_TZ defaults to True1, so Django stores times in Coordinated Universal Time (UTC) and converts them to the local time zone when you display them. A Saturday 9am booking in Limerick is still 9am after the clocks change.
Status goes into a CharField with choices. Django 5.0 simplified this: you can pass an enumeration class such as TextChoices straight to choices, without the .choices suffix earlier versions needed1.
Django 5.0 also added two field features that move work into the database19:
db_defaultsets a default that the database computes, such as the current time withNow(). It also applies when a row is inserted outside the ORM. If you set bothdefaultanddb_default,defaultwins when you create the object in Python, anddb_defaultstill guards the database9.GeneratedFieldis a column the database always computes from other columns in the same row. It takes anexpression, anoutput_fieldanddb_persist. In Django 5.0 you must setdb_persistexplicitly toTrueorFalse, and PostgreSQL only supports persisted (stored) columns910. Because the database computes the value, you reload the object withrefresh_from_db()to see it after saving9.
Example: the job card status and the part usage line total
The job card status is a short list of states. The parts used on a job card carry a price snapshot, because Niamh changes part prices and an old invoice must not change with them.
# repairs/models.py (first part)
from django.db import models
from django.db.models import Q
class JobStatus(models.TextChoices):
WAITING = "waiting", "Waiting"
IN_REPAIR = "in_repair", "In repair"
READY = "ready", "Ready"
COLLECTED = "collected", "Collected"
class JobCard(models.Model):
booking = models.OneToOneField(
"bookings.Booking", on_delete=models.PROTECT, related_name="job_card"
)
# Django 5.0: pass the enum itself, no ".choices" needed.
status = models.CharField(max_length=20, choices=JobStatus, default=JobStatus.WAITING)
notes = models.TextField(blank=True)
parts = models.ManyToManyField(
"parts.Part", through="parts.PartUsage", related_name="job_cards"
)
class Meta:
constraints = [
# The database refuses any status that is not on the list.
models.CheckConstraint(
check=Q(status__in=JobStatus.values), name="job_card_status_valid"
),
]
JobStatus sits at module level on purpose: the nested class Meta cannot see names defined inside the JobCard class body, so a status enum defined inside the model would not be reachable from its constraints.
# parts/models.py
from django.db import models
from django.db.models import F, Q
class Part(models.Model):
sku = models.CharField(max_length=40, unique=True)
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=8, decimal_places=2) # up to 999,999.99
stock_quantity = models.IntegerField(default=0)
reorder_level = models.IntegerField(default=5)
class Meta:
constraints = [
models.CheckConstraint(
check=Q(stock_quantity__gte=0), name="part_stock_never_negative"
),
]
class PartUsage(models.Model):
job_card = models.ForeignKey(
"repairs.JobCard", on_delete=models.CASCADE, related_name="part_usages"
)
part = models.ForeignKey(Part, on_delete=models.PROTECT, related_name="usages")
quantity = models.PositiveIntegerField()
unit_price = models.DecimalField(max_digits=8, decimal_places=2) # price snapshot
line_total = models.GeneratedField( # new in Django 5.0
expression=F("quantity") * F("unit_price"),
output_field=models.DecimalField(max_digits=10, decimal_places=2),
db_persist=True, # PostgreSQL only supports stored generated columns
)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["job_card", "part"], name="one_usage_row_per_part_per_card"
),
models.CheckConstraint(
check=Q(quantity__gt=0),
name="usage_quantity_positive",
violation_error_message="A part needs a quantity of at least one.",
),
]
Two things are worth noticing. The stock rule (never below zero) is a database constraint, so no door can break it, and it becomes the backbone of the stock example later. And line_total can never disagree with quantity and unit price, whoever writes the row, because nobody writes it at all.
Relationships: ForeignKey, on_delete and many to many with through
A ForeignKey is a "belongs to" link: a booking belongs to one customer. Django creates a database index on every foreign key automatically9, which matters when you filter by it. The required on_delete argument decides what happens to the booking when someone deletes the customer. It is a business decision dressed as a technical one, so decide it deliberately for each relationship.
| Option | What happens to the rows that point at the deleted row | Use it when |
|---|---|---|
CASCADE | They are deleted too | The child means nothing alone (a photo of a job card) |
PROTECT | Deletion is refused with ProtectedError | History must survive (bookings, invoices) |
RESTRICT | Refused, unless the child is also being deleted through a cascade in the same operation | Fine grained cases, rare |
SET_NULL | The link is set to empty (needs null=True) | The link is optional (a former mechanic on old notes) |
SET_DEFAULT, SET() | The link is set to a default or a value you give | A placeholder record exists |
DO_NOTHING | Django does nothing, so the database may raise an error | You manage it in SQL yourself |
The descriptions follow the field reference9. A useful habit: CASCADE only where the child is part of the parent, PROTECT everywhere money or history is involved.
A ManyToManyField links many to many: a job card uses many parts, a part appears on many job cards. Django creates a hidden join table for you. When the link itself carries data, quantity and price in our case, you name your own join model with through. The documentation calls this the most common use of the option, and it recommends a UniqueConstraint over the two foreign keys if one pair should appear only once9. That is exactly the one_usage_row_per_part_per_card constraint above.
Example: why bookings PROTECT their customer
A manager tries to delete a customer who has three past bookings, perhaps to tidy up a duplicate record.
>>> from bookings.models import Customer
>>> Customer.objects.get(email="duplicate@freewheelcycles.example").delete()
Traceback (most recent call last):
...
django.db.models.deletion.ProtectedError: ("Cannot delete some instances of model
'Customer' because they are referenced through protected foreign keys: ...
The refusal is the feature. Bookings are linked to job cards, job cards to invoices, and an invoice has to stay readable. The right move is to merge the duplicate into the real record (point the bookings at it) and then delete the empty one. With CASCADE the same click would have wiped three repairs and their invoices without a word.
Constraints and validation: the trap in save()
The first section gave you the doors. This section shows the trap in code, because it catches experienced developers coming from Rails, Laravel or a form heavy Django background.
full_clean() runs four steps in order: clean_fields(), clean(), validate_unique() and validate_constraints(), and raises one ValidationError with the errors from all four2. Forms call it. save() does not2.
There are two kinds of rule, and they belong in different places:
- Rules about one row (a status from a list, a quantity above zero, an end after the start, a unique email) go into
Meta.constraintsor field options such asunique=True. The database enforces them, andfull_clean()checks them too. - Rules that need other rows or outside knowledge (a mechanic must work at the booking's workshop, a slot must fall inside opening hours) go into
clean()or a service function. The database cannot easily see them, so you callfull_clean()yourself in every door you write.
One more detail from the constraints reference: you can give each constraint a violation_error_message and, new in Django 5.0, a violation_error_code, so a form shows a sentence a customer understands rather than "Constraint is violated"101.
Example: the same bad row through three doors
Cian opens the Django shell and tries to save a part usage with a quantity of zero, through three different doors.
>>> from parts.models import Part, PartUsage
>>> from repairs.models import JobCard
>>> card = JobCard.objects.first()
>>> tube = Part.objects.get(sku="TUBE-700x28")
# Door 1: full_clean(), what a ModelForm or the admin would do.
>>> usage = PartUsage(job_card=card, part=tube, quantity=0, unit_price=tube.price)
>>> usage.full_clean()
django.core.exceptions.ValidationError: {'__all__': ['A part needs a quantity
of at least one.']}
# Door 2: plain save(), no validation in Python at all.
>>> usage.save()
django.db.utils.IntegrityError: new row for relation "parts_partusage"
violates check constraint "usage_quantity_positive"
# Door 3: a bulk update, which skips save() entirely.
>>> PartUsage.objects.filter(job_card=card).update(quantity=0)
django.db.utils.IntegrityError: ... violates check constraint "usage_quantity_positive"
Without the CheckConstraint, door 1 would still catch it (the field is a PositiveIntegerField, so full_clean() would complain about a negative number, but zero is allowed) and doors 2 and 3 would write the zero quietly. With it, every door stops. Cian did not write a single line of validation code.
Migrations: makemigrations, migrate, data migrations and squashing
The Django documentation suggests thinking of migrations as "a version control system for your database schema"11. makemigrations packages your model changes into migration files, much like commits, and migrate applies them to the database (or unapplies them)11. Two habits make this safe on a team:
- Read the SQL before you trust it:
python manage.py sqlmigrate parts 0002prints what a migration will run. - Let continuous integration (CI) refuse a model change without its migration:
python manage.py makemigrations --check --dry-runexits with an error when a migration is missing.
On PostgreSQL every migration runs inside a transaction by default, because PostgreSQL supports transactional schema changes. MySQL and Oracle do not, so a migration that fails halfway there can leave the schema half changed11.
Data migrations change rows rather than columns. Django cannot generate them, so you write a RunPython operation11. Two rules from the documentation matter. First, use the historical model with apps.get_model(), never an import of your current model, because the current model may have fields this point in history does not know about. Old migrations would break the next time someone builds a fresh database. Historical models also have none of your custom methods11. Second, give RunPython a second callable for going backwards, or migrating back will raise an error11. migrations.RunPython.noop is the built in "nothing to undo".
Squashing reduces a long chain of migrations to one or a few that represent the same changes. squashmigrations writes a new file marked as replacing the old ones. The documented process is to squash while keeping the old files, release, wait until every environment has run that release, and only then delete the old files and release again11.
Example: adding the price snapshot to a live database
In the first version, Freewheel's part usages had no unit_price: invoices read the part's current price. After the first price change, Niamh saw an old invoice change its total. The fix is the unit_price snapshot from the model above, added to a table that already holds thousands of rows. It takes three migrations.
Step one, add the column as nullable, so existing rows are valid. Aisling temporarily sets null=True on unit_price and runs python manage.py makemigrations parts, which writes 0002_partusage_unit_price.
Step two, an empty migration for the data, created with python manage.py makemigrations parts --empty --name backfill_unit_price, then filled in:
# parts/migrations/0003_backfill_unit_price.py
from django.db import migrations
from django.db.models import OuterRef, Subquery
def copy_current_prices(apps, schema_editor):
# The historical models, never "from parts.models import ..."
Part = apps.get_model("parts", "Part")
PartUsage = apps.get_model("parts", "PartUsage")
current_price = Part.objects.filter(pk=OuterRef("part_id")).values("price")[:1]
# One UPDATE statement for every row, instead of a loop of saves.
PartUsage.objects.filter(unit_price__isnull=True).update(
unit_price=Subquery(current_price)
)
class Migration(migrations.Migration):
dependencies = [("parts", "0002_partusage_unit_price")]
operations = [
# Going backwards there is nothing to undo: the column is dropped by 0002.
migrations.RunPython(copy_current_prices, migrations.RunPython.noop),
]
Step three, Aisling removes null=True again and runs makemigrations, which writes 0004 making the column NOT NULL. The GeneratedField for line_total arrives in 0005, once unit_price is guaranteed to be filled.
One honest note for Niamh: the backfill copies today's price, not the price on the day of each repair, because that price was never stored. Old invoices are frozen from now on, at today's figures. That is a business decision, and it belongs in the commit message.
Managers and QuerySets: lazy, chainable, and named after the page
A manager is the gateway to a model's rows: Booking.objects is the default one. Calling a method on it returns a QuerySet, a description of a query that has not run yet. The documentation is clear that QuerySets are lazy: creating one involves no database activity, and you can stack filters "all day long" until the QuerySet is evaluated12. Each refinement returns a brand new QuerySet, so you can store and reuse the steps12. Evaluation happens when you iterate, slice with a step, call len(), list() or bool(), or render it in a template. After that, the QuerySet caches its results, so a second loop over the same object does not query again12.
Laziness is a gift for composing queries and a trap for performance. A template that loops over card.part_usages.all looks like plain attribute access, but it is a new query for every card. The documentation points this out: callable attributes such as entry.authors.all() query every time13.
The way out is a custom QuerySet whose methods are named after what the caller needs. My rule of thumb: name the shape, not just the filter. A method like for_board() carries the filter, the ordering and the loading strategy together, so the page that uses it cannot forget half of it.
Example: the board QuerySet
# repairs/models.py (second part)
from django.db import models
class JobCardQuerySet(models.QuerySet):
def open(self):
return self.exclude(status=JobStatus.COLLECTED)
def on_day(self, workshop_id, day):
return self.filter(
booking__workshop_id=workshop_id,
booking__starts_at__date=day, # converted in the current time zone
)
def for_board(self, workshop_id, day):
# The shape the workshop board needs: filter, order and load together.
return (
self.open()
.on_day(workshop_id, day)
.select_related("booking__customer")
.order_by("booking__starts_at")
)
class JobCard(models.Model):
# ... fields as above ...
objects = JobCardQuerySet.as_manager()
JobCard.objects.for_board(3, today) now builds one QuerySet out of small, testable pieces, and none of them touches the database until the template loops over it. The next sections explain why select_related is in there.
F and Q expressions: let the database do the arithmetic
An F() expression refers to a column's value inside the database, not to the copy in your Python object12. The model instance reference shows why that matters: expressing an update relative to the original value avoids a race condition and is slightly faster2. A Q() object wraps a condition so you can combine conditions with | (or), & (and) and ~ (not), because keyword arguments in filter() are always joined with and12.
The race that F() prevents is called a lost update. Two processes read the same value, both compute a new value from it, and the second write silently overwrites the first.
Example: the last inner tube
The Castletroy workshop has one 700x28 inner tube left. At 10.14am two mechanics fit one each, on two different job cards. With read, change, write code:
part = Part.objects.get(sku="TUBE-700x28") # both read stock_quantity = 1
part.stock_quantity -= 1 # both compute 0
part.save() # both write 0
The stock says zero, but two tubes left the shelf, and the shelf had one. The stock count is now wrong by one, and the nightly reorder report will be wrong with it. With F() and the constraint from earlier, the database does the arithmetic and refuses the impossible:
# parts/services.py
from django.db import IntegrityError, transaction
from django.db.models import F
from .models import Part, PartUsage
class OutOfStock(Exception):
pass
def fit_part(job_card, part, quantity=1):
try:
with transaction.atomic():
# "stock_quantity = stock_quantity - 1", computed inside the database.
Part.objects.filter(pk=part.pk).update(
stock_quantity=F("stock_quantity") - quantity
)
PartUsage.objects.create(
job_card=job_card, part=part, quantity=quantity, unit_price=part.price
)
except IntegrityError:
# The CheckConstraint refused a negative stock (or the part is already
# on this card): nothing was written, the transaction rolled back.
raise OutOfStock(part.sku)
The first mechanic's update takes the stock to zero. The second one would take it to minus one, the part_stock_never_negative constraint refuses, the transaction rolls back, and the second mechanic sees "out of stock" on the tablet instead of a phantom tube. Note that the try sits around the atomic() block, not inside it, exactly as the transactions documentation advises14.
And Q() for the front desk search, where a customer gives a name or an email:
from django.db.models import Q
term = "brennan"
Customer.objects.filter(Q(name__icontains=term) | Q(email__icontains=term))
annotate and aggregate: counting in the database
aggregate() turns a whole QuerySet into a few summary values and returns a dictionary. annotate() adds a computed value to every row, which is how you count or sum per group. Both run in the database, which is what the optimisation guide asks for: do database work in the database rather than in Python13.
One trap is documented and worth learning before it bites: combining several aggregations in one annotate() across different relationships gives wrong results, because Django uses joins rather than subqueries, and the joins multiply rows15. Two Count()s over two different "many" relationships in one query will inflate each other. Use one aggregation per relationship, or a subquery.
Example: the manager's week at a glance
Niamh wants, per mechanic for this week at one workshop: bookings, and jobs finished. And for the whole chain: what the parts on this week's job cards are worth.
from django.db.models import Count, Q, Sum
from bookings.models import Booking
from parts.models import PartUsage
from repairs.models import JobStatus
week = Booking.objects.filter(
workshop_id=workshop_id, starts_at__gte=monday, starts_at__lt=next_monday,
cancelled_at__isnull=True,
)
per_mechanic = (
week.values("mechanic__display_name") # group by mechanic
.annotate(
bookings=Count("id"),
finished=Count(
"id", filter=Q(job_card__status__in=[JobStatus.READY, JobStatus.COLLECTED])
),
)
.order_by("-bookings")
)
# One query: [{'mechanic__display_name': 'Seán', 'bookings': 41, 'finished': 37}, ...]
parts_value = PartUsage.objects.filter(
job_card__booking__starts_at__gte=monday,
job_card__booking__starts_at__lt=next_monday,
).aggregate(total=Sum("line_total"))
# {'total': Decimal('11730.50')} (illustrative figure, in euro)
Both counts run over the same relationship (bookings to their one job card), so the join trap does not apply. The filter= argument on Count is conditional aggregation: one pass, two numbers. And Sum("line_total") adds up the generated column, so the figure can never disagree with the individual lines.
The N+1 problem: from 61 queries to 3
Now the slow page. The workshop board shows today's open job cards at one workshop, each with its time slot and the customer's name. On a busy Saturday at the Castletroy workshop that is 29 cards. Aisling's first version, before the QuerySet from earlier existed:
# repairs/views.py (first version)
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils import timezone
from .models import JobCard, JobStatus
@login_required
def board(request, workshop_id):
cards = (
JobCard.objects.filter(
booking__workshop_id=workshop_id,
booking__starts_at__date=timezone.localdate(),
)
.exclude(status=JobStatus.COLLECTED)
.order_by("booking__starts_at")
)
return render(request, "repairs/board.html", {"cards": cards})
<!-- repairs/templates/repairs/board.html (extract) -->
{% for card in cards %}
<article class="job-card job-card--{{ card.status }}">
<time>{{ card.booking.starts_at|time:"H:i" }}</time>
<h3>{{ card.booking.customer.name }}</h3>
<p>{{ card.get_status_display }}</p>
</article>
{% endfor %}
The page took about 420ms on a laptop with a full Saturday of data (an illustrative figure, not a benchmark). Django Debug Toolbar, version 4.3.0 at the time of writing16, showed why. Its SQL panel listed "61 queries including 58 similar". The toolbar calls queries similar when they share the same SQL with different parameters, and duplicates when even the parameters are the same17. Here is how the 61 broke down:
- 1 query to load the session, and 1 to load the logged in user (the
login_requiredcheck). Every logged in page pays these two. - 1 query for the job cards. It joins the bookings table, but only to filter. A join in the
WHEREclause is not a join in theSELECT: the booking columns are not loaded. - Then, for each of the 29 cards, 1 query for
card.booking(to show the time) and 1 forbooking.customer(to show the name). That is 58 similar queries, two shapes of SQL repeated 29 times each.
That is the N+1 problem: one query for the list, plus one more for every row (here, two more for every row). You can write it as a formula. It looks like overkill for counting queries, but it shows the one term that matters.
where is the number of queries for a page with rows, is the fixed cost every page pays (here the session and the user, so ), the is the query for the list itself, is the number of lazily loaded relationships each row touches (here booking and customer, so ), and is the number of rows (here 29 job cards). Foundations: ratios and rates
With Freewheel's numbers:
The term to kill is . As long as it is there, the page gets slower every time the business gets busier, which is the worst possible moment. A page's query count should not contain . That is the test I would hold every list page to.
The fix is the for_board() QuerySet with select_related("booking__customer"). It follows the foreign keys from job card to booking to customer inside the one query, with joins, so the related objects arrive already filled4.
# repairs/views.py (fixed)
@login_required
def board(request, workshop_id):
cards = JobCard.objects.for_board(workshop_id, timezone.localdate())
return render(request, "repairs/board.html", {"cards": cards})
The template does not change at all. The toolbar now shows 3 queries: session, user, and one job card query with two INNER JOINs. The page renders in about 60ms on the same laptop (again illustrative). With :
The term is now zero, so no longer depends on at all: 3 queries for 29 cards, and 3 for 290.
The more telling picture is what happens as the business grows. Without the fix, the query count climbs with every card. With it, the line stays flat.
Example: a test that keeps the board at 3 queries
A fix that nobody guards comes undone the first time someone adds a field to the template. Django's test case has assertNumQueries, which asserts exactly how many queries a block of code runs18. The trick I recommend: assert the same number at two sizes. If the count is the same with 2 cards and with 12, it does not contain , whatever the exact number is.
# repairs/tests/test_board_queries.py
import datetime as dt
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from bookings.models import Bike, Booking, Customer
from repairs.models import JobCard
from workshops.models import Mechanic, Workshop
class BoardQueryCountTest(TestCase):
def setUp(self):
# Use the fields your custom user model defines.
user = get_user_model().objects.create_user(username="niamh", password="x")
self.client.force_login(user)
self.workshop = Workshop.objects.create(name="Castletroy", city="Limerick")
self.mechanic = Mechanic.objects.create(
user=user, workshop=self.workshop, display_name="Seán"
)
self.made = 0
def add_cards(self, count):
# 8am local time today, so every card lands on today's board.
start = timezone.localtime().replace(hour=8, minute=0, second=0, microsecond=0)
for _ in range(count):
self.made += 1
customer = Customer.objects.create(
name=f"Customer {self.made}", email=f"c{self.made}@example.test"
)
bike = Bike.objects.create(customer=customer, make="Trek")
slot = start + dt.timedelta(minutes=15 * self.made)
booking = Booking.objects.create(
workshop=self.workshop, mechanic=self.mechanic, customer=customer,
bike=bike, starts_at=slot, ends_at=slot + dt.timedelta(minutes=15),
)
JobCard.objects.create(booking=booking)
def test_query_count_does_not_grow_with_cards(self):
url = reverse("repairs:board", args=[self.workshop.id])
self.add_cards(2)
with self.assertNumQueries(3): # session, user, job cards
self.client.get(url)
self.add_cards(10)
with self.assertNumQueries(3): # still 3 with 12 cards
self.client.get(url)
If someone later adds {{ card.booking.bike.make }} to the template, the test fails at the second assertion and names the extra queries in its message. The fix is one more name in select_related. The testing chapters later in the programme build on this pattern.
select_related or prefetch_related: the one question to ask
Django gives you two tools for loading related rows up front, and the documentation explains the difference precisely. select_related creates an SQL join and includes the related object's fields in the same SELECT, so it is limited to single valued relationships: ForeignKey and OneToOneField. prefetch_related does a separate lookup for each relationship and does the joining in Python, which makes it work for many to many and reverse foreign keys too4.
That gives one question that settles almost every case: from the row you have, does the relationship point at one thing or at many? One means a join is safe, because each row stays one row. Many means a join would repeat each row once per child, so a second query is better.
Rails developers know the same pair under other names. In Active Record, eager_load loads associations with a LEFT OUTER JOIN, preload uses one query per association, and includes picks one of the two for you19. So select_related is Django's eager_load for single links, and prefetch_related is Django's preload. Django has no includes that chooses for you, which fits its preference for explicit code.
Example: Niamh asks for the before photos
A month after launch, Niamh wants a thumbnail of the "before" photo on every board card, so the mechanic can spot the bike in the rack. A job card has many photos (a reverse foreign key from JobCardPhoto), and only the "before" ones are wanted.
from django.db.models import Prefetch
from repairs.models import JobCardPhoto
class JobCardQuerySet(models.QuerySet):
# ... open() and on_day() as before ...
def for_board(self, workshop_id, day):
before_photos = JobCardPhoto.objects.filter(kind="before").order_by("id")
return (
self.open()
.on_day(workshop_id, day)
.select_related("booking__customer") # one: join
.prefetch_related( # many: second query
Prefetch("photos", queryset=before_photos, to_attr="before_photos")
)
.order_by("booking__starts_at")
)
In the template, card.before_photos is now a plain Python list, already filled. The page runs 4 queries: session, user, cards, and one query for all the before photos of all the cards, matched up in Python. Update the test to assertNumQueries(4) at both sizes, and it still proves the count does not grow with .
Loading less: only, defer, values and iterator
Loading the right rows is half the job. Loading only the columns and the amount of memory you need is the other half.
values()andvalues_list()return dictionaries or tuples instead of model objects. The optimisation guide recommends them when you only need the values13.only()anddefer()load model objects with some columns left out. The QuerySet reference calls them tools for advanced use, to be used cautiously, because a deferred field touched later is fetched with an extra query, one field at a time413. That turns them into an N+1 generator if you guess wrong.iterator()streams a large result instead of caching it all. Without a prefetch, Django fetches it in chunks of 2,000 rows by default4. If you also prefetch, you must passchunk_sizefor the prefetch to happen4.count()andexists()ask the database for one number or one yes, instead of loading every row to count them in Python13.
Example: the nightly reorder report
Every night at 2am, the reorder report lists every part at or below its reorder level, for the buyer at the central store. It needs four values per part, not 2,400 model objects.
from django.db.models import F
from parts.models import Part
low_stock = (
Part.objects.filter(stock_quantity__lte=F("reorder_level")) # compare two columns
.order_by("sku")
.values_list("sku", "name", "stock_quantity", "reorder_level")
)
for sku, name, stock, level in low_stock:
write_report_line(sku, name, stock, level)
One query, four columns, no model objects. The marketing export of 9,000 active customers is the place for iterator(): Customer.objects.order_by("id").values_list("name", "email").iterator() keeps memory flat however large the list becomes.
Bulk operations without surprises
Saving 2,400 parts one by one means 2,400 INSERT statements. The bulk methods send a few instead, and the optimisation guide recommends them13. They are also doors that skip save(), so read their caveats once, properly4:
bulk_create()does not callsave()and sends nopre_saveorpost_savesignals. On PostgreSQL the new primary keys are set on your objects, on some other databases they are not. It does not work with many to many relationships.batch_sizecontrols how many rows go in one statement.bulk_create()can also upsert: withupdate_conflicts=True,unique_fieldsandupdate_fields, an existing row is updated instead of failing.bulk_update()also skipssave()and signals, and can produce very large SQL if you update many columns on many rows, whichbatch_sizefixes.update()runs one SQLUPDATE, skipssave()and sends no signals.
Example: importing the parts list and the supplier price feed
On launch day, Cian imports the 2,400 parts from Niamh's spreadsheet. Because bulk_create() skips validation, he runs field validation per row first, but leaves uniqueness to the database, which avoids 2,400 extra lookups.
# parts/management/commands/import_parts.py (core)
from parts.models import Part
def import_rows(rows):
parts = []
for row in rows:
part = Part(sku=row["sku"].strip(), name=row["name"].strip(),
price=row["price"], stock_quantity=row["stock"])
# Field checks in Python; unique sku and stock rules are left to the database.
part.full_clean(validate_unique=False, validate_constraints=False)
parts.append(part)
Part.objects.bulk_create(parts, batch_size=500) # 5 INSERT statements
Every night after that, the supplier sends new prices for the parts it carries. One upsert keeps them current:
Part.objects.bulk_create(
incoming_parts, # Part objects built from the supplier file
update_conflicts=True,
unique_fields=["sku"],
update_fields=["price"], # existing rows: only the price changes
batch_size=500,
)
Because PartUsage stores its own unit_price, the nightly price update can never change an invoice. The model from earlier and this import were designed together.
Transactions: atomic and on_commit
By default Django runs in autocommit mode: every query is committed on its own. transaction.atomic() groups several queries into one transaction that either commits completely or rolls back completely, and you can use it as a decorator or a context manager14. You can also wrap every request in a transaction with the ATOMIC_REQUESTS database setting14. It is simple, but it holds a transaction open for the whole view, including template rendering, so I prefer explicit atomic() blocks around the writes that belong together.
Two rules from the documentation deserve a place on the wall14:
- Do not catch database errors inside an
atomic()block. If you swallow the exception inside, Django cannot tell that something went wrong. Put thetryaround the block, or nest an inneratomic()for the part that may fail. - Side effects go in
on_commit(). An email, a text message, a task for a background worker: register it withtransaction.on_commit()and it runs only after the transaction commits. If the transaction rolls back, the callback is discarded and never runs. Since Django 4.2,robust=Truelets later callbacks run even if one of them fails.
Example: "your bike is ready", sent only when it is true
When a mechanic moves a job card to "ready", the customer gets an email and a text message. Sending them inside the transaction would be a bug: if a later step fails and rolls back, the customer would be told about a bike that is not ready in the system.
# repairs/services.py
from functools import partial
from django.db import transaction
from notifications.services import send_bike_ready # email and text message
from .models import JobCard, JobStatus
def mark_ready(job_card_id):
with transaction.atomic():
card = JobCard.objects.select_for_update().get(pk=job_card_id)
card.status = JobStatus.READY
card.save(update_fields=["status"])
# Runs after COMMIT, never after a rollback.
transaction.on_commit(partial(send_bike_ready, card.pk))
select_for_update() locks the job card row until the transaction ends, so two mechanics tapping the same card at the same moment cannot both send the message. It only works inside a transaction, and Django raises an error if you evaluate it in autocommit mode4. The chapter on background tasks later in this series moves send_bike_ready onto a task queue, and the on_commit() line stays exactly where it is.
Indexes and EXPLAIN: measure, then index
An index lets the database find rows without reading the whole table. Django creates some for you: every ForeignKey gets one9, and every unique field or UniqueConstraint is backed by a unique index. Others you declare in Meta.indexes. The optimisation guide is careful about the order: indexes are the number one priority, but only after profiling has shown which ones you need13. Its first advice is to find out what queries you run and what they cost, with QuerySet.explain() or a tool such as Django Debug Toolbar13.
explain() returns the database's execution plan for a QuerySet: how it would run the query, including which indexes and joins it would use. It works on every built in backend except Oracle. On PostgreSQL you can pass flags such as analyze=True, which executes the query, and the documentation warns that this can change data if triggers or functions are involved4. One more caution: on a near empty development database, PostgreSQL often prefers to read the whole table because it is faster at that size. Run explain() against realistic volumes.
The old index_together option is deprecated since Django 4.2 in favour of Meta.indexes, and the documentation notes that UniqueConstraint offers more than unique_together, which "may be deprecated in the future"20. New code should use indexes and constraints.
Example: the board query on a year of bookings
Freewheel takes about 1,150 bookings a week, which is close to 60,000 a year. Aisling loads a year of realistic test data and asks PostgreSQL how it runs the board query:
>>> from datetime import date
>>> qs = JobCard.objects.for_board(workshop_id=3, day=date(2024, 4, 13))
>>> print(qs.explain())
-- abridged and illustrative
Nested Loop
-> Nested Loop
-> Index Scan using booking_workshop_start_idx on bookings_booking
Index Cond: (workshop_id = 3)
Filter: (((starts_at AT TIME ZONE 'Europe/Dublin'))::date = '2024-04-13'::date)
-> Index Scan using repairs_jobcard_booking_id_key on repairs_jobcard
Filter: (status <> 'collected')
-> Index Scan using bookings_customer_pkey on bookings_customer
Two lessons are in that plan. The composite index on workshop and start time does the heavy lifting, and that index exists because the board filters exactly by those two columns. But the Filter line shows the date comparison applied after the scan: filtering with starts_at__date wraps the column in a time zone conversion, which the index cannot use. Aisling changes on_day() to a range, starts_at__gte=start_of_day, starts_at__lt=start_of_next_day, computed in the workshop's time zone, and the date moves into the Index Cond. Measure, change one thing, measure again.
The same ideas in Active Record
If you read the Rails chapter first, or you know Rails, this table maps the concepts. Both columns describe documented behaviour as of Rails 7.1 and Django 5.0.
| Concept | Active Record (Rails 7.1) | Django ORM (5.0) |
|---|---|---|
| Pattern | Active Record, after Fowler | Active Record, after Fowler, per Django's design philosophies |
| Source of the schema | Hand written migrations, schema.rb generated | Model classes, migrations generated by makemigrations |
| Validation on save | Yes, save runs validations by default | No, save() skips full_clean() |
| Skipping validation | update_all, insert_all, update_column and others | update(), bulk_create(), bulk_update(), plain save() |
| Load one via join | eager_load | select_related |
| Load many via second query | preload | prefetch_related |
| Let the framework choose | includes | No equivalent, you choose |
| Forbid lazy loading | strict_loading raises an error | Nothing built in, assertNumQueries in tests |
| Side effect after commit | after_commit callback | transaction.on_commit() |
The Rails behaviour is described in the Rails Guides for validations and for querying619. The row that matters most is the third. A Rails developer moving to Django has to unlearn the assumption that saving validates. A Django developer moving to Rails has to learn that callbacks and validations fire on every save, wanted or not.
For the person paying for this
You do not need to read model code to judge whether your data layer is healthy. Ask your developer five questions, and listen for concrete answers.
| Question | A good answer sounds like |
|---|---|
| Which business rules does the database itself enforce? | "Double bookings, stock below zero, invalid statuses: all in Meta.constraints." |
| How do you know a list page will not slow down as we grow? | "Each list page has a query count test at two sizes." |
| What happens if someone deletes a customer with invoices? | "Deletion is refused; we merge or anonymise instead." |
| Can a missing migration reach production? | "No, CI runs makemigrations --check." |
| Is money stored as decimals, and are old prices kept on invoices? | "Yes, DecimalField, with a price snapshot on every line." |
If the answers are vague, the risk is not that the application is broken today. It is that it will break quietly on your busiest day. If you are commissioning a web application and want this level of care built in from the first model, I build web applications on Ruby on Rails, with the same principles: constraints in the database, tests written first, and the code, accounts and data owned by you.
My view
Separating what is documented from what is my judgement: everything above about how Django behaves comes from the Django documentation for 5.0 and the release notes. The rules of thumb are mine.
My view: the Django ORM is one of the best things in Django, and its explicitness is a strength once you accept the cost. The models file is the most readable schema description in either framework. GeneratedField and db_default in 5.0 push more truth into the database, which is the right direction. And Django 4.1's change to validate Meta.constraints inside full_clean() quietly fixed the biggest practical problem, because now one declaration gives you a friendly form error and a hard database guarantee.
What it asks of you is discipline in three places. Know your doors, and put every rule that costs money into the database. Name your QuerySets after the pages that use them, so the loading strategy travels with the filter. And pin every list page with a query count test at two sizes, because the N+1 problem does not announce itself until the busiest Saturday of the year.
Rails, which I build with, makes the first of those easier by validating on save and the third easier with strict_loading. Django makes the schema easier to read and the migration history easier to generate. A senior developer in either camp will recognise every rule in this chapter, because underneath both ORMs there is the same database, and the database is the only part that sees every door.
Conclusion
Model your data in Django the way you would want to audit it later. Money in DecimalField, time with time zones on, statuses as TextChoices backed by a CheckConstraint. Every rule that would cost money goes into Meta.constraints, because save(), update(), the bulk methods and Django REST Framework all skip full_clean(), and only the database guards every door. Write migrations in small steps, data migrations with historical models and a way back, and squash only after every environment has caught up.
Then keep it fast. QuerySets are lazy, so decide the loading strategy where you build them: select_related when the link points at one object, prefetch_related when it points at many. Count queries with Django Debug Toolbar, write the count down as , and remove the . Freewheel's board went from 61 queries to 3 without touching the template, and a test at two sizes keeps it there. Do arithmetic in the database with F(), wrap writes that belong together in atomic(), send messages in on_commit(), and add indexes after explain() has told you where they belong.
The next chapter turns these models into a working back office with the Django admin, and shows where that back office stops.
