Django ORM
This chapter moves from model metadata and migrations to precise QuerySet semantics, expressions, aggregation, relationship loading, custom managers, SQL plans, and measurable query-count control.
- Explain Models & migrations by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain QuerySets & lookups by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Annotations & aggregations by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain selectrelated & prefetchrelated by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom managers by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Django ORM, read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the framework learning arc appropriate to this subject.
The problem this chapter solves
This chapter moves from model metadata and migrations to precise QuerySet semantics, expressions, aggregation, relationship loading, custom managers, SQL plans, and measurable query-count control.
It removes repeated infrastructure work and gives teams conventions for evolving a database-backed product safely. DRF extends the same model to HTTP APIs.
Learning outcomes
- Explain Models & migrations by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain QuerySets & lookups by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Annotations & aggregations by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain select_related & prefetch_related by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Custom managers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Field, lookup & plan reference by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
A server adapts an HTTP or ASGI event into HttpRequest, middleware wraps the request in configured order, URL resolution selects a view, the view coordinates forms or serializers and lazy QuerySets, and a response unwinds through middleware. The ORM compiles QuerySet expressions into parameterized SQL; evaluation materializes model instances and may populate relation caches. In Django ORM, use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- Django loads settings, initializes the app registry, composes middleware, and registers URL patterns before accepting the request.
- The URL resolver selects a view; authentication, permission, form, or serializer code converts untrusted request data into validated Python values.
- The view or service constructs a lazy QuerySet or enters a transaction; SQL is generated, planned by PostgreSQL, executed, and mapped back into model or projection values.
- On success the transaction commits and the response is rendered or serialized; on failure it rolls back and Django's exception path produces the documented error contract.
- Middleware unwinds around the response, while tests assert status, body, durable rows, query count, permissions, and any on-commit asynchronous handoff.
Memory and performance lens
Django model instances and serializer data are ordinary Python heap objects scoped to a request unless cached. QuerySets are lazy and hold a query plan, not rows, until evaluated. Careless list conversion, prefetching, or template iteration can materialize large result sets and create high per-worker memory pressure. For Django ORM, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Django ORM, measure request p50/p95/p99, validation failures, database query count, pool saturation, response size, and error rate by contract rather than optimizing from source-code appearance.
1. Models & migrations
The Models & migrations unit begins with all field types and Meta class: A migration is versioned code that moves database schema or data from one known state to the next. Deploy backward-compatible expand/migrate/contract changes for large systems. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Models & migrations
| Concept | Meaning | Engineering decision |
|---|---|---|
| all field types and Meta class | A migration is versioned code that moves database schema or data from one known state to the next. | Deploy backward-compatible expand/migrate/contract changes for large systems. |
| migration internals: makemigrations/migrate/showmigrations | A migration is versioned code that moves database schema or data from one known state to the next. | Deploy backward-compatible expand/migrate/contract changes for large systems. |
| RunPython data migrations | A migration is versioned code that moves database schema or data from one known state to the next. | Deploy backward-compatible expand/migrate/contract changes for large systems. |
Follow the request through the framework: Models & migrations
all field types and Meta class. Django compares model state to migration state, builds operations, and uses a backend schema editor. Historical models in RunPython differ from current imported models.
migration internals: makemigrations/migrate/showmigrations. Django compares model state to migration state, builds operations, and uses a backend schema editor. Historical models in RunPython differ from current imported models.
RunPython data migrations. Django compares model state to migration state, builds operations, and uses a backend schema editor. Historical models in RunPython differ from current imported models.
Read these as one system: all field types and Meta class establishes the starting contract, migration internals: makemigrations/migrate/showmigrations changes how that contract is executed or represented, and RunPython data migrations exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Models & migrations
1@transaction.atomic2def all_field_types_and_meta_class(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_all_field_types_and_meta_class(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Models & migrations slice makes all field types and Meta class observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward RunPython data migrations, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Models & migrations
| Risk | Why it matters |
|---|---|
| all field types and Meta class | Renames can be misdetected as delete-plus-create; inspect generated operations before applying. |
| migration internals: makemigrations/migrate/showmigrations | Renames can be misdetected as delete-plus-create; inspect generated operations before applying. |
| RunPython data migrations | Renames can be misdetected as delete-plus-create; inspect generated operations before applying. |
Framework lab: Models & migrations
- Foundation: implement or demonstrate all field types and Meta class with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine all field types and Meta class with migration internals: makemigrations/migrate/showmigrations. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for RunPython data migrations. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. QuerySets & lookups
The QuerySets & lookups unit begins with filter/exclude/get + field lookups (__icontains/__gte/__in): A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. Push filtering and projection to SQL while keeping queries observable. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: QuerySets & lookups
| Concept | Meaning | Engineering decision |
|---|---|---|
| filter/exclude/get + field lookups (__icontains/__gte/__in) | A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. | Push filtering and projection to SQL while keeping queries observable. |
| Q objects for OR/AND/NOT | A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. | Push filtering and projection to SQL while keeping queries observable. |
| values()/values_list()/only()/defer() | A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. | Push filtering and projection to SQL while keeping queries observable. |
Follow the request through the framework: QuerySets & lookups
filter/exclude/get + field lookups (__icontains/__gte/__in). Each refinement clones query state; iteration, slicing with a step, length, truth testing, or serialization may execute SQL. Cached results belong to that QuerySet instance.
Q objects for OR/AND/NOT. Each refinement clones query state; iteration, slicing with a step, length, truth testing, or serialization may execute SQL. Cached results belong to that QuerySet instance.
values()/values_list()/only()/defer(). Each refinement clones query state; iteration, slicing with a step, length, truth testing, or serialization may execute SQL. Cached results belong to that QuerySet instance.
Read these as one system: filter/exclude/get + field lookups (__icontains/__gte/__in) establishes the starting contract, Q objects for OR/AND/NOT changes how that contract is executed or represented, and values()/values_list()/only()/defer() exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: QuerySets & lookups
1Post.objects.filter(status="published").select_related("author")This QuerySets & lookups slice makes filter/exclude/get + field lookups (__icontains/__gte/__in) observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward values()/values_list()/only()/defer(), predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: QuerySets & lookups
| Risk | Why it matters |
|---|---|
| filter/exclude/get + field lookups (__icontains/__gte/__in) | get() requires exactly one row; only/defer can create surprise follow-up queries. |
| Q objects for OR/AND/NOT | get() requires exactly one row; only/defer can create surprise follow-up queries. |
| values()/values_list()/only()/defer() | get() requires exactly one row; only/defer can create surprise follow-up queries. |
Framework lab: QuerySets & lookups
- Foundation: implement or demonstrate filter/exclude/get + field lookups (__icontains/__gte/__in) with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine filter/exclude/get + field lookups (__icontains/__gte/__in) with Q objects for OR/AND/NOT. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for values()/values_list()/only()/defer(). State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
3. Annotations & aggregations
The Annotations & aggregations unit begins with aggregate() vs annotate(): ORM expressions ask the database to compute values atomically and set-wise. Inspect generated SQL when combining joins and counts. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Annotations & aggregations
| Concept | Meaning | Engineering decision |
|---|---|---|
| aggregate() vs annotate() | ORM expressions ask the database to compute values atomically and set-wise. | Inspect generated SQL when combining joins and counts. |
| Count/Sum/Avg + Case/When | ORM expressions ask the database to compute values atomically and set-wise. | Inspect generated SQL when combining joins and counts. |
| F expressions and Subquery/OuterRef | ORM expressions ask the database to compute values atomically and set-wise. | Inspect generated SQL when combining joins and counts. |
Follow the request through the framework: Annotations & aggregations
aggregate() vs annotate(). aggregate collapses a QuerySet to summary values; annotate extends each result row and can change grouping. F references a column without a read-modify-write race.
Count/Sum/Avg + Case/When. aggregate collapses a QuerySet to summary values; annotate extends each result row and can change grouping. F references a column without a read-modify-write race.
F expressions and Subquery/OuterRef. aggregate collapses a QuerySet to summary values; annotate extends each result row and can change grouping. F references a column without a read-modify-write race.
Read these as one system: aggregate() vs annotate() establishes the starting contract, Count/Sum/Avg + Case/When changes how that contract is executed or represented, and F expressions and Subquery/OuterRef exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Annotations & aggregations
1Category.objects.annotate(review_count=Count("products__reviews"))This Annotations & aggregations slice makes aggregate() vs annotate() observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward F expressions and Subquery/OuterRef, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Annotations & aggregations
| Risk | Why it matters |
|---|---|
| aggregate() vs annotate() | Multiple joins can multiply rows; use distinct or subqueries only after proving the intended cardinality. |
| Count/Sum/Avg + Case/When | Multiple joins can multiply rows; use distinct or subqueries only after proving the intended cardinality. |
| F expressions and Subquery/OuterRef | Multiple joins can multiply rows; use distinct or subqueries only after proving the intended cardinality. |
Framework lab: Annotations & aggregations
- Foundation: implement or demonstrate aggregate() vs annotate() with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine aggregate() vs annotate() with Count/Sum/Avg + Case/When. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for F expressions and Subquery/OuterRef. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
4. select_related & prefetch_related
The select_related & prefetch_related unit begins with N+1 problem detection with debug-toolbar: N+1 occurs when one initial query triggers one additional relation query per result. Choose loading based on access pattern and assert query counts on important endpoints. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: select_related & prefetch_related
| Concept | Meaning | Engineering decision |
|---|---|---|
| N+1 problem detection with debug-toolbar | N+1 occurs when one initial query triggers one additional relation query per result. | Choose loading based on access pattern and assert query counts on important endpoints. |
| select_related for FK (SQL JOIN) | N+1 occurs when one initial query triggers one additional relation query per result. | Choose loading based on access pattern and assert query counts on important endpoints. |
| prefetch_related for M2M/reverse FK | N+1 occurs when one initial query triggers one additional relation query per result. | Choose loading based on access pattern and assert query counts on important endpoints. |
| assertNumQueries in tests | N+1 occurs when one initial query triggers one additional relation query per result. | Choose loading based on access pattern and assert query counts on important endpoints. |
Follow the request through the framework: select_related & prefetch_related
N+1 problem detection with debug-toolbar. select_related uses SQL joins for single-valued relations; prefetch_related executes secondary queries and joins objects in Python for multi-valued relations.
select_related for FK (SQL JOIN). select_related uses SQL joins for single-valued relations; prefetch_related executes secondary queries and joins objects in Python for multi-valued relations.
prefetch_related for M2M/reverse FK. select_related uses SQL joins for single-valued relations; prefetch_related executes secondary queries and joins objects in Python for multi-valued relations.
assertNumQueries in tests. select_related uses SQL joins for single-valued relations; prefetch_related executes secondary queries and joins objects in Python for multi-valued relations.
Read these as one system: N+1 problem detection with debug-toolbar establishes the starting contract, select_related for FK (SQL JOIN) changes how that contract is executed or represented, and assertNumQueries in tests exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: select_related & prefetch_related
1@transaction.atomic2def n_1_problem_detection_with_debug_toolbar(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_n_1_problem_detection_with_debug_toolbar(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis select_related & prefetch_related slice makes N+1 problem detection with debug-toolbar observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward assertNumQueries in tests, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: select_related & prefetch_related
| Risk | Why it matters |
|---|---|
| N+1 problem detection with debug-toolbar | Blind prefetching can allocate huge object graphs and be slower than targeted queries. |
| select_related for FK (SQL JOIN) | Blind prefetching can allocate huge object graphs and be slower than targeted queries. |
| prefetch_related for M2M/reverse FK | Blind prefetching can allocate huge object graphs and be slower than targeted queries. |
| assertNumQueries in tests | Blind prefetching can allocate huge object graphs and be slower than targeted queries. |
Framework lab: select_related & prefetch_related
- Foundation: implement or demonstrate N+1 problem detection with debug-toolbar with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine N+1 problem detection with debug-toolbar with select_related for FK (SQL JOIN). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for assertNumQueries in tests. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
5. Custom managers
The Custom managers unit begins with Manager vs QuerySet methods: A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. Push filtering and projection to SQL while keeping queries observable. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Custom managers
| Concept | Meaning | Engineering decision |
|---|---|---|
| Manager vs QuerySet methods | A QuerySet is an immutable, chainable description of a database query that is evaluated lazily. | Push filtering and projection to SQL while keeping queries observable. |
| chaining custom managers | Managers and custom QuerySets encode reusable query vocabulary; soft deletion hides rows while preserving data. | Provide an explicit all-objects manager and define uniqueness semantics. |
| soft delete manager pattern | Managers and custom QuerySets encode reusable query vocabulary; soft deletion hides rows while preserving data. | Provide an explicit all-objects manager and define uniqueness semantics. |
Follow the request through the framework: Custom managers
Manager vs QuerySet methods. Each refinement clones query state; iteration, slicing with a step, length, truth testing, or serialization may execute SQL. Cached results belong to that QuerySet instance.
chaining custom managers. A manager is the model entry point and can return a custom QuerySet whose methods stay chainable. Soft delete usually writes a timestamp or state.
soft delete manager pattern. A manager is the model entry point and can return a custom QuerySet whose methods stay chainable. Soft delete usually writes a timestamp or state.
Read these as one system: Manager vs QuerySet methods establishes the starting contract, chaining custom managers changes how that contract is executed or represented, and soft delete manager pattern exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Custom managers
1Post.objects.filter(status="published").select_related("author")This Custom managers slice makes Manager vs QuerySet methods observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward soft delete manager pattern, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Custom managers
| Risk | Why it matters |
|---|---|
| Manager vs QuerySet methods | get() requires exactly one row; only/defer can create surprise follow-up queries. |
| chaining custom managers | Hidden rows still occupy constraints and relations; soft delete is not a complete retention policy. |
| soft delete manager pattern | Hidden rows still occupy constraints and relations; soft delete is not a complete retention policy. |
Framework lab: Custom managers
- Foundation: implement or demonstrate Manager vs QuerySet methods with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Manager vs QuerySet methods with chaining custom managers. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for soft delete manager pattern. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
6. Field, lookup & plan reference
The Field, lookup & plan reference unit begins with core relational and PostgreSQL field types: Django fields declare Python conversion, validation, database column type, form behavior, defaults, nullability, uniqueness, and migration metadata. Choose the narrowest field that models the domain, add database constraints for durable invariants, and review generated migrations and SQL. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The framework contract: Field, lookup & plan reference
| Concept | Meaning | Engineering decision |
|---|---|---|
| core relational and PostgreSQL field types | Django fields declare Python conversion, validation, database column type, form behavior, defaults, nullability, uniqueness, and migration metadata. | Choose the narrowest field that models the domain, add database constraints for durable invariants, and review generated migrations and SQL. |
| exact/iexact/contains/range/date/regex/isnull lookups | Field lookups are the operators after a double underscore in QuerySet filters; they translate typed Python values into parameterized SQL predicates. | Use lookups to keep filtering declarative, but inspect SQL and plans for case-insensitive, substring, regex, date-transform, and nullable predicates. |
| EXPLAIN vs EXPLAIN ANALYZE | MVCC gives transactions snapshots of tuple versions; WAL records changes for crash recovery and replication; vacuum reclaims versions no active snapshot needs. | Use EXPLAIN (ANALYZE, BUFFERS) safely on representative data and tune autovacuum per table when needed. |
| reading Seq Scan/Index Scan/joins/sort/buffers | An execution plan explains how PostgreSQL reads rows, joins relations, sorts data, and uses memory or cache buffers for a QuerySet. | Use plans on representative data when latency or query count matters; begin with the first node whose estimate, loop count, or I/O is unexpectedly large. |
Follow the request through the framework: Field, lookup & plan reference
core relational and PostgreSQL field types. Each field contributes descriptors to the model class and schema operations to migrations. PostgreSQL-specific fields and constraints compile to native types and operators, while relations create key columns and reverse accessors.
exact/iexact/contains/range/date/regex/isnull lookups. Django resolves transforms and lookups from the model field, prepares the right-hand value, quotes identifiers, and delegates parameter binding to the database driver. Index usability depends on the operator and expression.
EXPLAIN vs EXPLAIN ANALYZE. Each plan node exposes estimated and actual rows, loops, time, buffers, and sometimes disk spill. pg_stat_statements aggregates normalized query statistics.
reading Seq Scan/Index Scan/joins/sort/buffers. EXPLAIN (ANALYZE, BUFFERS) executes the SQL and records estimates versus actual rows, loops, timing, shared-buffer hits/reads, and spill information for every plan node.
Read these as one system: core relational and PostgreSQL field types establishes the starting contract, exact/iexact/contains/range/date/regex/isnull lookups changes how that contract is executed or represented, and reading Seq Scan/Index Scan/joins/sort/buffers exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
A focused implementation slice: Field, lookup & plan reference
1@transaction.atomic2def core_relational_and_postgresql_field_types(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_core_relational_and_postgresql_field_types(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Field, lookup & plan reference slice makes core relational and PostgreSQL field types observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward reading Seq Scan/Index Scan/joins/sort/buffers, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Field, lookup & plan reference
| Risk | Why it matters |
|---|---|
| core relational and PostgreSQL field types | Confusing null=True with blank=True, using float for money, or changing a populated column without a migration plan causes invalid or unavailable data. |
| exact/iexact/contains/range/date/regex/isnull lookups | A convenient lookup can force a full scan; isnull does not mean empty string, and regex supplied by users needs length and timeout controls. |
| EXPLAIN vs EXPLAIN ANALYZE | A long transaction prevents cleanup, and EXPLAIN ANALYZE executes the statement. |
| reading Seq Scan/Index Scan/joins/sort/buffers | Reading only the top cost or assuming every sequential scan is bad leads to unnecessary indexes and slower writes. |
Framework lab: Field, lookup & plan reference
- Foundation: implement or demonstrate core relational and PostgreSQL field types with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine core relational and PostgreSQL field types with exact/iexact/contains/range/date/regex/isnull lookups. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for reading Seq Scan/Index Scan/joins/sort/buffers. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1from django.db.models import Avg, Count, F, Q2
3categories = (4 Category.objects5 .filter(Q(products__stock__gt=0) | Q(featured=True))6 .annotate(7 product_count=Count("products", distinct=True),8 average_rating=Avg("products__reviews__rating"),9 )10 .filter(product_count__gte=3)11 .order_by(F("average_rating").desc(nulls_last=True), "id")12)13
14for category in categories:15 print(category.name, category.product_count, category.average_rating)Expected result
1One grouped SQL query returns qualifying categories with counts and average ratings.Line-by-line reading
| Line | Code | Explanation | |
|---|---|---|---|
| 1 | from django.db.models import Avg, Count, F, Q | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. | |
| 3 | categories = ( | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 4 | Category.objects | Implements the next python statement in the example's data flow. | |
| 5 | `.filter(Q(products__stock__gt=0) \ | Q(featured=True))` | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 6 | .annotate( | Implements the next python statement in the example's data flow. | |
| 7 | product_count=Count("products", distinct=True), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 8 | average_rating=Avg("products__reviews__rating"), | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 9 | ) | Implements the next python statement in the example's data flow. | |
| 10 | .filter(product_count__gte=3) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 11 | .order_by(F("average_rating").desc(nulls_last=True), "id") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. | |
| 12 | ) | Implements the next python statement in the example's data flow. | |
| 14 | for category in categories: | Consumes the iterable one item at a time through the iterator protocol. | |
| 15 | print(category.name, category.product_count, category.average_rating) | Emits the example's observable output. |
Step-by-step execution
- Django loads settings, initializes the app registry, composes middleware, and registers URL patterns before accepting the request.
- The URL resolver selects a view; authentication, permission, form, or serializer code converts untrusted request data into validated Python values.
- The view or service constructs a lazy QuerySet or enters a transaction; SQL is generated, planned by PostgreSQL, executed, and mapped back into model or projection values.
- On success the transaction commits and the response is rendered or serialized; on failure it rolls back and Django's exception path produces the documented error contract.
- Middleware unwinds around the response, while tests assert status, body, durable rows, query count, permissions, and any on-commit asynchronous handoff.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Models & migrations | Renames can be misdetected as delete-plus-create; inspect generated operations before applying. | Deploy backward-compatible expand/migrate/contract changes for large systems. |
| QuerySets & lookups | get() requires exactly one row; only/defer can create surprise follow-up queries. | Push filtering and projection to SQL while keeping queries observable. |
| Annotations & aggregations | Multiple joins can multiply rows; use distinct or subqueries only after proving the intended cardinality. | Inspect generated SQL when combining joins and counts. |
| select_related & prefetch_related | Blind prefetching can allocate huge object graphs and be slower than targeted queries. | Choose loading based on access pattern and assert query counts on important endpoints. |
| Custom managers | get() requires exactly one row; only/defer can create surprise follow-up queries. | Push filtering and projection to SQL while keeping queries observable. |
| Field, lookup & plan reference | Confusing null=True with blank=True, using float for money, or changing a populated column without a migration plan causes invalid or unavailable data. | Choose the narrowest field that models the domain, add database constraints for durable invariants, and review generated migrations and SQL. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the E-commerce ORM Challenge project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Models & migrations: all field types and Meta class
- To do: Models & migrations: migration internals: makemigrations/migrate/showmigrations
- To do: Models & migrations: RunPython data migrations
- To do: QuerySets & lookups: filter/exclude/get + field lookups (__icontains/__gte/__in)
- To do: QuerySets & lookups: Q objects for OR/AND/NOT
- To do: QuerySets & lookups: values()/values_list()/only()/defer()
- To do: Annotations & aggregations: aggregate() vs annotate()
- To do: Annotations & aggregations: Count/Sum/Avg + Case/When
- To do: Annotations & aggregations: F expressions and Subquery/OuterRef
- To do: select_related & prefetch_related: N+1 problem detection with debug-toolbar
- To do: select_related & prefetch_related: select_related for FK (SQL JOIN)
- To do: select_related & prefetch_related: prefetch_related for M2M/reverse FK
- To do: select_related & prefetch_related: assertNumQueries in tests
- To do: Custom managers: Manager vs QuerySet methods
- To do: Custom managers: chaining custom managers
- To do: Custom managers: soft delete manager pattern
- To do: Field, lookup & plan reference: core relational and PostgreSQL field types
- To do: Field, lookup & plan reference: exact/iexact/contains/range/date/regex/isnull lookups
- To do: Field, lookup & plan reference: EXPLAIN vs EXPLAIN ANALYZE
- To do: Field, lookup & plan reference: reading Seq Scan/Index Scan/joins/sort/buffers
Quick revision
- Models & migrations: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- QuerySets & lookups: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Annotations & aggregations: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- select_related & prefetch_related: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Custom managers: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Field, lookup & plan reference: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?