Project Workshop — E-commerce ORM Challenge
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
Django · PostgreSQL · ORM
Expected effort: 5–8 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | all field types and Meta class produces the specified behavior inside Models & migrations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | migration internals: makemigrations/migrate/showmigrations produces the specified behavior inside Models & migrations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | RunPython data migrations produces the specified behavior inside Models & migrations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | filter/exclude/get + field lookups (__icontains/__gte/__in) produces the specified behavior inside QuerySets & lookups | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | Q objects for OR/AND/NOT produces the specified behavior inside QuerySets & lookups | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | values()/values_list()/only()/defer() produces the specified behavior inside QuerySets & lookups | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | aggregate() vs annotate() produces the specified behavior inside Annotations & aggregations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | Count/Sum/Avg + Case/When produces the specified behavior inside Annotations & aggregations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | F expressions and Subquery/OuterRef produces the specified behavior inside Annotations & aggregations | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | N+1 problem detection with debug-toolbar produces the specified behavior inside select_related & prefetch_related | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | select_related for FK (SQL JOIN) produces the specified behavior inside select_related & prefetch_related | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | prefetch_related for M2M/reverse FK produces the specified behavior inside select_related & prefetch_related | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.4 | assertNumQueries in tests produces the specified behavior inside select_related & prefetch_related | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | Manager vs QuerySet methods produces the specified behavior inside Custom managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | chaining custom managers produces the specified behavior inside Custom managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | soft delete manager pattern produces the specified behavior inside Custom managers | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.1 | core relational and PostgreSQL field types produces the specified behavior inside Field, lookup & plan reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.2 | exact/iexact/contains/range/date/regex/isnull lookups produces the specified behavior inside Field, lookup & plan reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.3 | EXPLAIN vs EXPLAIN ANALYZE produces the specified behavior inside Field, lookup & plan reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-6.4 | reading Seq Scan/Index Scan/joins/sort/buffers produces the specified behavior inside Field, lookup & plan reference | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── manage.py3├── config/{settings,urls,asgi,celery}.py4├── domain/5│ ├── models.py6│ ├── services.py7│ ├── selectors.py8│ ├── serializers-or-schema.py9│ ├── views-or-resolvers.py10│ ├── permissions.py11│ ├── tasks.py12│ └── consumers.py13├── templates/14├── tests/{unit,api,integration}/15├── pyproject.toml16└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Models & migrations | all field types and Meta class; migration internals: makemigrations/migrate/showmigrations; RunPython data migrations | Demonstration plus focused tests |
| 2 | QuerySets & lookups | filter/exclude/get + field lookups (__icontains/__gte/__in); Q objects for OR/AND/NOT; values()/values_list()/only()/defer() | Demonstration plus focused tests |
| 3 | Annotations & aggregations | aggregate() vs annotate(); Count/Sum/Avg + Case/When; F expressions and Subquery/OuterRef | Demonstration plus focused tests |
| 4 | select_related & prefetch_related | N+1 problem detection with debug-toolbar; select_related for FK (SQL JOIN); prefetch_related for M2M/reverse FK | Demonstration plus focused tests |
| 5 | Custom managers | Manager vs QuerySet methods; chaining custom managers; soft delete manager pattern | Demonstration plus focused tests |
| 6 | Field, lookup & plan reference | core relational and PostgreSQL field types; exact/iexact/contains/range/date/regex/isnull lookups; EXPLAIN vs EXPLAIN ANALYZE | Demonstration plus focused tests |
| 7 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
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.Code 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. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| 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 | Hidden rows still occupy constraints and relations; soft delete is not a complete retention policy. | Provide an explicit all-objects manager and define uniqueness semantics. |
| Field, lookup & plan reference | Reading only the top cost or assuming every sequential scan is bad leads to unnecessary indexes and slower writes. | 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. |
Engineering checklist for this stack
- To do: authenticate before object lookup where possible
- To do: authorize the action and object server-side
- To do: keep transactions in the application service
- To do: bound request, response, and query work
- To do: map typed domain failures to stable protocol errors
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1def test_list_is_authorized_and_query_bounded(api_client, member, project, django_assert_num_queries):2 api_client.force_authenticate(member)3 with django_assert_num_queries(3):4 response = api_client.get("/api/resources/")5 assert response.status_code == 2006 assert all(item["project_id"] == str(project.id) for item in response.data["results"])Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?