Django REST Framework
This chapter develops an API as a chain of input validation, authentication, authorization, throttling, query planning, serialization, pagination, and response contracts.
- Explain Serializers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain APIView vs ViewSets by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Authentication & permissions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Throttling & pagination by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Routers & custom authentication by naming its input, guarantee, internal lifecycle, important failure, and proof.
How to use this chapter
For Django REST Framework, 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 develops an API as a chain of input validation, authentication, authorization, throttling, query planning, serialization, pagination, and response contracts.
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 Serializers by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain APIView vs ViewSets by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Authentication & permissions by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Throttling & pagination by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Routers & custom authentication 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 REST Framework, 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 REST Framework, connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Django REST Framework, 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. Serializers
The Serializers unit begins with Serializer vs ModelSerializer: A DRF serializer defines external representation, input coercion, validation, and creation/update behavior. Use separate read and write serializers when contracts diverge. 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: Serializers
| Concept | Meaning | Engineering decision |
|---|---|---|
| Serializer vs ModelSerializer | A DRF serializer defines external representation, input coercion, validation, and creation/update behavior. | Use separate read and write serializers when contracts diverge. |
| field-level and object-level validation | Field validation checks one serializer value; object validation checks relationships among the already converted fields. | Use field hooks for local rules and validate() for cross-field rules, returning the normalized attributes or raising a structured ValidationError. |
| nested serializers (read vs write) | A DRF serializer defines external representation, input coercion, validation, and creation/update behavior. | Use separate read and write serializers when contracts diverge. |
| SerializerMethodField | A DRF serializer defines external representation, input coercion, validation, and creation/update behavior. | Use separate read and write serializers when contracts diverge. |
Follow the request through the framework: Serializers
Serializer vs ModelSerializer. Fields validate first, object validation sees their result, and save() calls create or update. Nested writes require explicit transaction-aware behavior.
field-level and object-level validation. DRF runs field parsing and validators before calling validate_, then builds an attribute dictionary for validate(). Database constraints remain necessary for race-sensitive invariants.
nested serializers (read vs write). Fields validate first, object validation sees their result, and save() calls create or update. Nested writes require explicit transaction-aware behavior.
SerializerMethodField. Fields validate first, object validation sees their result, and save() calls create or update. Nested writes require explicit transaction-aware behavior.
Read these as one system: Serializer vs ModelSerializer establishes the starting contract, field-level and object-level validation changes how that contract is executed or represented, and SerializerMethodField 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: Serializers
1class ItemSerializer(serializers.ModelSerializer):2 class Meta: model = Item; fields = ("id", "name")This Serializers slice makes Serializer vs ModelSerializer 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 SerializerMethodField, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Serializers
| Risk | Why it matters |
|---|---|
| Serializer vs ModelSerializer | SerializerMethodField can create N+1 queries and undocumented business logic. |
| field-level and object-level validation | Performing authorization in a validation hook or relying only on a pre-insert uniqueness query creates mixed responsibilities and races. |
| nested serializers (read vs write) | SerializerMethodField can create N+1 queries and undocumented business logic. |
| SerializerMethodField | SerializerMethodField can create N+1 queries and undocumented business logic. |
Framework lab: Serializers
- Foundation: implement or demonstrate Serializer vs ModelSerializer with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine Serializer vs ModelSerializer with field-level and object-level validation. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for SerializerMethodField. 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. APIView vs ViewSets
The APIView vs ViewSets unit begins with APIView manual method handling: DRF view abstractions trade explicit control for reusable CRUD conventions and router-generated URLs. Start with the narrowest abstraction that keeps permissions and queries obvious. 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: APIView vs ViewSets
| Concept | Meaning | Engineering decision |
|---|---|---|
| APIView manual method handling | DRF view abstractions trade explicit control for reusable CRUD conventions and router-generated URLs. | Start with the narrowest abstraction that keeps permissions and queries obvious. |
| GenericAPIView + mixins | URL configuration maps path patterns to callables; class-based views assemble behavior through dispatch and mixins. | Name every public route and reverse it instead of hard-coding URLs. |
| ModelViewSet full CRUD | DRF view abstractions trade explicit control for reusable CRUD conventions and router-generated URLs. | Start with the narrowest abstraction that keeps permissions and queries obvious. |
| @action decorator for custom endpoints | A decorator receives a callable or class and returns a replacement, usually adding cross-cutting behavior. | Use it for orthogonal policy such as timing, authorization, validation, retry, or caching. |
Follow the request through the framework: APIView vs ViewSets
APIView manual method handling. APIView dispatches methods; GenericAPIView adds queryset/serializer hooks; mixins implement actions; a ViewSet binds actions to methods through a router.
GenericAPIView + mixins. Resolvers test patterns in order. A CBV's as_view() returns a callable that instantiates the class and dispatches by HTTP method. Mixin order affects MRO.
ModelViewSet full CRUD. APIView dispatches methods; GenericAPIView adds queryset/serializer hooks; mixins implement actions; a ViewSet binds actions to methods through a router.
@action decorator for custom endpoints. Decoration runs when the definition is executed, not at each call; the returned wrapper is what the name references. wraps preserves metadata and the wrapped chain.
Read these as one system: APIView manual method handling establishes the starting contract, GenericAPIView + mixins changes how that contract is executed or represented, and @action decorator for custom endpoints 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: APIView vs ViewSets
1@transaction.atomic2def apiview_manual_method_handling(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_apiview_manual_method_handling(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis APIView vs ViewSets slice makes APIView manual method handling 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 @action decorator for custom endpoints, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: APIView vs ViewSets
| Risk | Why it matters |
|---|---|
| APIView manual method handling | Never expose an unrestricted ModelViewSet merely because routing is convenient. |
| GenericAPIView + mixins | Place access-control mixins before generic view bases and avoid overly clever inheritance chains. |
| ModelViewSet full CRUD | Never expose an unrestricted ModelViewSet merely because routing is convenient. |
| @action decorator for custom endpoints | Keep retries bounded and restricted to transient, idempotent operations. |
Framework lab: APIView vs ViewSets
- Foundation: implement or demonstrate APIView manual method handling with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine APIView manual method handling with GenericAPIView + mixins. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for @action decorator for custom endpoints. 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. Authentication & permissions
The Authentication & permissions unit begins with JWT with djangorestframework-simplejwt: Token authentication proves possession of a signed credential; authorization separately decides whether that identity may perform an action. Enforce object ownership and roles on the server for every path. 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: Authentication & permissions
| Concept | Meaning | Engineering decision |
|---|---|---|
| JWT with djangorestframework-simplejwt | Token authentication proves possession of a signed credential; authorization separately decides whether that identity may perform an action. | Enforce object ownership and roles on the server for every path. |
| access + refresh tokens | Token authentication proves possession of a signed credential; authorization separately decides whether that identity may perform an action. | Enforce object ownership and roles on the server for every path. |
| IsAuthenticated/IsAdminUser/custom permission_classes | Token authentication proves possession of a signed credential; authorization separately decides whether that identity may perform an action. | Enforce object ownership and roles on the server for every path. |
Follow the request through the framework: Authentication & permissions
JWT with djangorestframework-simplejwt. A server validates signature, issuer, audience, expiry, and claims. Short-lived access tokens limit exposure; rotating refresh tokens require server-side reuse detection or revocation state.
access + refresh tokens. A server validates signature, issuer, audience, expiry, and claims. Short-lived access tokens limit exposure; rotating refresh tokens require server-side reuse detection or revocation state.
IsAuthenticated/IsAdminUser/custom permission_classes. A server validates signature, issuer, audience, expiry, and claims. Short-lived access tokens limit exposure; rotating refresh tokens require server-side reuse detection or revocation state.
Read these as one system: JWT with djangorestframework-simplejwt establishes the starting contract, access + refresh tokens changes how that contract is executed or represented, and IsAuthenticated/IsAdminUser/custom permission_classes 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: Authentication & permissions
1@transaction.atomic2def jwt_with_djangorestframework_simplejwt(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_jwt_with_djangorestframework_simplejwt(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Authentication & permissions slice makes JWT with djangorestframework-simplejwt 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 IsAuthenticated/IsAdminUser/custom permission_classes, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Authentication & permissions
| Risk | Why it matters |
|---|---|
| JWT with djangorestframework-simplejwt | Decoding is not validation, and a valid token does not grant every resource. |
| access + refresh tokens | Decoding is not validation, and a valid token does not grant every resource. |
| IsAuthenticated/IsAdminUser/custom permission_classes | Decoding is not validation, and a valid token does not grant every resource. |
Framework lab: Authentication & permissions
- Foundation: implement or demonstrate JWT with djangorestframework-simplejwt with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine JWT with djangorestframework-simplejwt with access + refresh tokens. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for IsAuthenticated/IsAdminUser/custom permission_classes. 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. Throttling & pagination
The Throttling & pagination unit begins with AnonRateThrottle/UserRateThrottle/ScopedRateThrottle: Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. Use deterministic unique ordering and return retry metadata. 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: Throttling & pagination
| Concept | Meaning | Engineering decision |
|---|---|---|
| AnonRateThrottle/UserRateThrottle/ScopedRateThrottle | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| custom Redis throttle | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
| PageNumber/LimitOffset/CursorPagination | Throttling bounds request rate; pagination bounds response and query work. Cursor pagination advances from a stable ordering key rather than a row offset. | Use deterministic unique ordering and return retry metadata. |
Follow the request through the framework: Throttling & pagination
AnonRateThrottle/UserRateThrottle/ScopedRateThrottle. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
custom Redis throttle. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
PageNumber/LimitOffset/CursorPagination. Distributed limits use atomic counters or scripts. A cursor encodes ordering position and tie-breaker; Relay exposes edges, nodes, cursors, and pageInfo.
Read these as one system: AnonRateThrottle/UserRateThrottle/ScopedRateThrottle establishes the starting contract, custom Redis throttle changes how that contract is executed or represented, and PageNumber/LimitOffset/CursorPagination 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: Throttling & pagination
1@transaction.atomic2def anonratethrottle_userratethrottle_scopedra(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_anonratethrottle_userratethrottle_scopedra(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Throttling & pagination slice makes AnonRateThrottle/UserRateThrottle/ScopedRateThrottle 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 PageNumber/LimitOffset/CursorPagination, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Throttling & pagination
| Risk | Why it matters |
|---|---|
| AnonRateThrottle/UserRateThrottle/ScopedRateThrottle | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| custom Redis throttle | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
| PageNumber/LimitOffset/CursorPagination | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. |
Framework lab: Throttling & pagination
- Foundation: implement or demonstrate AnonRateThrottle/UserRateThrottle/ScopedRateThrottle with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine AnonRateThrottle/UserRateThrottle/ScopedRateThrottle with custom Redis throttle. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for PageNumber/LimitOffset/CursorPagination. 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. Routers & custom authentication
The Routers & custom authentication unit begins with DefaultRouter and SimpleRouter: DRF view abstractions trade explicit control for reusable CRUD conventions and router-generated URLs. Start with the narrowest abstraction that keeps permissions and queries obvious. 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: Routers & custom authentication
| Concept | Meaning | Engineering decision |
|---|---|---|
| DefaultRouter and SimpleRouter | DRF view abstractions trade explicit control for reusable CRUD conventions and router-generated URLs. | Start with the narrowest abstraction that keeps permissions and queries obvious. |
| writable nested create/update transactions | Writable nested serializers coordinate changes to a parent and related children; DRF requires explicit create() and update() semantics because ownership, deletion, and identity are domain decisions. | Use nested writes only when the client operation is genuinely atomic and define omitted-versus-deleted behavior explicitly. |
| custom BaseAuthentication contract | A DRF BaseAuthentication implementation converts request credentials into (user, auth) or returns None when it did not attempt that authentication scheme. | Use a custom authenticator only for a real credential protocol, validate expiry/audience/signature or lookup state, and keep object access decisions in permissions. |
| authentication vs permission vs object permission | Authentication establishes who is calling, general permission checks whether that principal may use the action, and object permission checks the action against one concrete resource. | Apply all three layers deliberately and test collection, detail, create, update, delete, and custom actions with the wrong user or tenant. |
Follow the request through the framework: Routers & custom authentication
DefaultRouter and SimpleRouter. APIView dispatches methods; GenericAPIView adds queryset/serializer hooks; mixins implement actions; a ViewSet binds actions to methods through a router.
writable nested create/update transactions. Validated nested dictionaries do not save automatically. The service enters one database transaction, creates or locks the parent, matches children by permitted identifiers, applies additions/updates/removals, and commits only after all constraints pass.
custom BaseAuthentication contract. DRF tries configured authenticators in order. A recognized but invalid credential should raise AuthenticationFailed; successful identity is stored on the lazy request.user and request.auth properties before permission checks.
authentication vs permission vs object permission. DRF authenticates first, runs has_permission() before the view body, then calls check_object_permissions() only when view code retrieves an object through the expected hooks. QuerySet filtering remains necessary to avoid listing unauthorized rows.
Read these as one system: DefaultRouter and SimpleRouter establishes the starting contract, writable nested create/update transactions changes how that contract is executed or represented, and authentication vs permission vs object permission 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: Routers & custom authentication
1@transaction.atomic2def defaultrouter_and_simplerouter(*, actor: User, data: dict[str, object]) -> Result:3 validated = validate_defaultrouter_and_simplerouter(data)4 result = repository.apply(actor=actor, data=validated)5 return resultThis Routers & custom authentication slice makes DefaultRouter and SimpleRouter 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 authentication vs permission vs object permission, predict its behavior for empty, invalid, repeated, and large input.
Where production applications break: Routers & custom authentication
| Risk | Why it matters |
|---|---|
| DefaultRouter and SimpleRouter | Never expose an unrestricted ModelViewSet merely because routing is convenient. |
| writable nested create/update transactions | Calling child saves without one transaction or accepting arbitrary child IDs can leave partial state or modify another owner's relation. |
| custom BaseAuthentication contract | Returning None for an invalid recognized credential can let a later authenticator or anonymous path accept a request that should be rejected. |
| authentication vs permission vs object permission | Defining has_object_permission() is ineffective if custom view code never invokes the object-permission check. |
Framework lab: Routers & custom authentication
- Foundation: implement or demonstrate DefaultRouter and SimpleRouter with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine DefaultRouter and SimpleRouter with writable nested create/update transactions. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for authentication vs permission vs object permission. 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 rest_framework import serializers, viewsets2from rest_framework.permissions import IsAuthenticated3
4class TaskWriteSerializer(serializers.ModelSerializer):5 class Meta:6 model = Task7 fields = ("id", "project", "title", "status")8 read_only_fields = ("id",)9
10 def validate_project(self, project):11 if not project.members.filter(pk=self.context["request"].user.pk).exists():12 raise serializers.ValidationError("not a project member")13 return project14
15class TaskViewSet(viewsets.ModelViewSet):16 serializer_class = TaskWriteSerializer17 permission_classes = (IsAuthenticated,)18
19 def get_queryset(self):20 return Task.objects.filter(project__members=self.request.user).select_related("project")Expected result
1Authenticated users see and mutate only tasks in projects where they are members.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | from rest_framework import serializers, viewsets | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from rest_framework.permissions import IsAuthenticated | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | class TaskWriteSerializer(serializers.ModelSerializer): | Creates a class namespace and binds the resulting class object to this name. |
| 5 | class Meta: | Creates a class namespace and binds the resulting class object to this name. |
| 6 | model = Task | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 7 | fields = ("id", "project", "title", "status") | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 8 | read_only_fields = ("id",) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 10 | def validate_project(self, project): | Defines a function; its parameters form the explicit input boundary. |
| 11 | if not project.members.filter(pk=self.context["request"].user.pk).exists(): | Evaluates the condition and enters this branch only when it is truthy. |
| 12 | raise serializers.ValidationError("not a project member") | Stops the happy path with a deliberate exception carrying the boundary failure. |
| 13 | return project | Returns the observable result to the caller and ends this invocation. |
| 15 | class TaskViewSet(viewsets.ModelViewSet): | Creates a class namespace and binds the resulting class object to this name. |
| 16 | serializer_class = TaskWriteSerializer | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 17 | permission_classes = (IsAuthenticated,) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 19 | def get_queryset(self): | Defines a function; its parameters form the explicit input boundary. |
| 20 | return Task.objects.filter(project__members=self.request.user).select_related("project") | Returns the observable result to the caller and ends this invocation. |
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 |
|---|---|---|
| Serializers | SerializerMethodField can create N+1 queries and undocumented business logic. | Use separate read and write serializers when contracts diverge. |
| APIView vs ViewSets | Never expose an unrestricted ModelViewSet merely because routing is convenient. | Start with the narrowest abstraction that keeps permissions and queries obvious. |
| Authentication & permissions | Decoding is not validation, and a valid token does not grant every resource. | Enforce object ownership and roles on the server for every path. |
| Throttling & pagination | Application throttles are not a substitute for edge protection, and offset pagination drifts under concurrent writes. | Use deterministic unique ordering and return retry metadata. |
| Routers & custom authentication | Never expose an unrestricted ModelViewSet merely because routing is convenient. | Start with the narrowest abstraction that keeps permissions and queries obvious. |
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 Task Management REST API 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: Serializers: Serializer vs ModelSerializer
- To do: Serializers: field-level and object-level validation
- To do: Serializers: nested serializers (read vs write)
- To do: Serializers: SerializerMethodField
- To do: APIView vs ViewSets: APIView manual method handling
- To do: APIView vs ViewSets: GenericAPIView + mixins
- To do: APIView vs ViewSets: ModelViewSet full CRUD
- To do: APIView vs ViewSets: @action decorator for custom endpoints
- To do: Authentication & permissions: JWT with djangorestframework-simplejwt
- To do: Authentication & permissions: access + refresh tokens
- To do: Authentication & permissions: IsAuthenticated/IsAdminUser/custom permission_classes
- To do: Throttling & pagination: AnonRateThrottle/UserRateThrottle/ScopedRateThrottle
- To do: Throttling & pagination: custom Redis throttle
- To do: Throttling & pagination: PageNumber/LimitOffset/CursorPagination
- To do: Routers & custom authentication: DefaultRouter and SimpleRouter
- To do: Routers & custom authentication: writable nested create/update transactions
- To do: Routers & custom authentication: custom BaseAuthentication contract
- To do: Routers & custom authentication: authentication vs permission vs object permission
Quick revision
- Serializers: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- APIView vs ViewSets: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Authentication & permissions: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Throttling & pagination: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Routers & custom authentication: 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?