Debug a Failing Django Film Catalog Filter API
System DesignModel answerLast updated
Fix defects in an existing Django REST API so that a suite of automated tests covering search, filtering, ordering, and error handling all pass.
Background
You have inherited a Django project that exposes a film catalog API. A colleague wrote the models, URL configuration, views, and a test suite before leaving the team. When you run the tests, several of them fail — some with assertion errors on the response body, others with HTTP 500 responses. Your job is to make every test pass by fixing the application code. You are not starting from scratch; the scaffolding is already there.
The endpoints accept an optional free-text search term and a set of filters (genre, director, writer, rating range, release year range) and always require a sort order for the results. Treat the test suite as the authoritative specification. If a test and your intuition disagree, trust the test.
You have 60 minutes.
What You Are Given
- Django models for films and their related entities (genre, director, writer)
- URL routing, view functions or class-based views, and serializers
- A test suite that covers multiple endpoints and parameter combinations
- The ability to run the full suite (
python manage.py test) or individual tests
What You Are Not Asked to Do
- Build any new models, endpoints, or migrations
- Modify the tests (assume they are correct and consistent)
Clarifying Questions to Raise Before You Start
Before writing a single fix, a strong candidate asks:
- Are the tests the complete specification, or is there also a written description of expected behavior?
- When a filter receives an invalid value (e.g.,
year=abc), should the endpoint return a 400 or silently ignore the filter? - Are text filters (genre, director, writer) exact-match or case-insensitive? Are numeric bounds inclusive or exclusive? Where in the tests would you look to find out?
Part 1 — Triage Before You Touch Anything
You run the full suite and see failures scattered across multiple endpoints. Before editing any code, how do you organize what you see? Walk through:
- How you group the failures to spot shared root causes
- The order in which you trace a single failing test from the assertion back to the source
- Which category of failure you fix first, and why
Part 2 — Filters Return Wrong or Duplicate Results
For each symptom below, describe what you inspect and what defect likely causes it:
- Requests that include filters but no search query return zero results or crash, while the same filters combined with a search term work fine.
- Filtering by genre, director, or writer returns the wrong films, or returns some films more than once.
- Films whose rating or year sits exactly on a boundary value are missing from results that should include them, or appear in results that should exclude them.
- One filter appears to be completely ignored — changing its value has no effect on the results.
Part 3 — Ordering and 500 Errors
The result sets are now correct, but some tests still fail because items are in the wrong order, and one endpoint returns HTTP 500 on certain inputs. How do you diagnose and fix each problem?
- How do you construct a deterministic sort that handles ties the same way the tests expect?
- How do you read a Django traceback to identify which layer caused the 500?
- How do you convert bad input into a proper 4xx client error instead of letting it crash?
Hints
Hint 1
Start by grouping test failures by endpoint and error type — assertion errors and 500s have different root causes and different fix strategies. Fix a 500 first because it blocks you from seeing whether the logic underneath is even right.
Hint 2
The most common sources of wrong filter results in Django are: (a) building the queryset inside an `if search_query` branch so filters are never applied without a query, (b) filtering across a ManyToMany or reverse FK without a `.distinct()`, and (c) using `=` where `__iexact` or `__gte`/`__lte` is needed.
Hint 3
For ordering, check whether the tests assert on a secondary sort key when the primary values tie. A single `order_by('rating')` can pass most cases but fail whenever two films share the same rating. Add a stable tie-breaker (e.g., `id`) that matches the expected order in the test fixtures.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach Overview
Debugging an unfamiliar codebase under time pressure is primarily a triage and tracing problem. The goal is to fix root causes — not to patch tests one by one. The right mental model is: group → trace → fix → re-run → repeat.
Part 1 — Triage First, Edit Second
Group failures before touching code.
Run the full suite and collect the output. Sort failures into buckets:
- HTTP 500 responses — these are crashes; something in the code raises an unhandled exception
- Wrong status code (e.g., 200 when 400 is expected, or 404 when 200 is expected) — likely a routing or input-validation gap
- Correct status but wrong body — the queryset or serializer is producing the wrong data
Fix 500s first. A crash in a shared code path (query building, serialization) can mask many other failures. Fixing one root cause may turn five red tests green.
Trace a single failing test layer by layer.
The stack goes: test assertion → HTTP response → view → queryset → model/database. Read it in that order:
- What exactly does the test assert? Print the actual response body next to the expected value.
- Does the URL even resolve? Check
urls.pyfor typos, missingpath()entries, or wrong view references. - Does the view extract the right parameters? Add a temporary
print(request.GET)or use the debugger. - Does the queryset return the right rows? Run the ORM query in the Django shell with the same inputs.
- Does the serializer render the right fields? Check field names, nested representations, and any
source=arguments.
Fix order heuristic: routing bugs → 500s → missing/wrong results → ordering. Each layer depends on the one before it.
Part 2 — Filters Return Wrong or Duplicate Results
Symptom 1: Filters only work when a search query is also present.
The most common cause is that the base queryset is constructed inside an if search_query: block:
# Broken
if search_query:
qs = Film.objects.filter(title__icontains=search_query)
if genre:
qs = qs.filter(genre__name__iexact=genre)
When search_query is empty, qs is never assigned. Fix by always starting from Film.objects.all() and applying the search term as one optional filter among many:
qs = Film.objects.all()
if search_query:
qs = qs.filter(title__icontains=search_query)
if genre:
qs = qs.filter(genre__name__iexact=genre)
Symptom 2: Wrong films or duplicate rows.
Filtering across a ManyToMany (e.g., genres) or a reverse FK (e.g., directors) causes Django to emit a JOIN. If a film has two matching rows in the joined table, it appears twice in the result. Fix with .distinct():
qs = qs.filter(directors__name__icontains=director).distinct()
Also verify the lookup path. If the model is Film with a directors M2M field pointing to a Person model, the lookup is directors__name, not director__name. A silent typo here returns every film (Django ignores an unrecognised lookup in some configurations) or raises a FieldError.
Symptom 3: Boundary values missing or wrongly included.
Check whether the test expects inclusive bounds. rating__gt=7 excludes a film rated exactly 7; rating__gte=7 includes it. Read the test fixture and the assertion carefully. The usual Django idiom for inclusive numeric ranges:
if min_rating:
qs = qs.filter(rating__gte=min_rating)
if max_rating:
qs = qs.filter(rating__lte=max_rating)
Also check type conversion. request.GET returns strings. Comparing a string "7.5" against a FloatField may work in SQLite but fail in stricter backends, or produce wrong ordering. Always cast: float(request.GET.get('min_rating')).
Symptom 4: A filter is ignored entirely.
Most likely causes in order of frequency:
- The parameter name in
request.GET.get(...)doesn't match what the test sends (e.g.,'Genre'vs'genre') - The filter is applied to a local variable that isn't assigned back:
qs.filter(...)is called but the return value is discarded - A logical short-circuit:
if genre and genre != 'all':silently skips the filter when the test sends the string'all'
Part 3 — Ordering and 500 Errors
Getting the sort order right.
If tests assert on a specific order, find the expected rows in the fixture and work backwards to identify the sort key(s). A single order_by('-rating') passes when all ratings differ, but fails when two films tie. Add a deterministic tie-breaker that matches the fixture:
qs = qs.order_by('-rating', 'title', 'id')
The id tie-breaker ensures the order is stable even when title also ties. Common mistake: forgetting that Django's default model ordering (set in Meta.ordering) can interfere with an explicit order_by. An explicit order_by in the view overrides Meta.ordering, which is usually what you want.
Reading a 500 traceback.
Django's test runner prints the full traceback. Read from the bottom up: the last frame is where the exception was raised; the frames above it show the call path through your code. Common 500 sources in this kind of API:
ValueErrorfromint('abc')orfloat('')— a filter parameter wasn't validated before type conversionFieldErrorfrom a misspelled ORM lookup — caught at queryset evaluation time, not at the.filter()callKeyErrororAttributeErrorin the serializer — a field is missing or named differently on the model
Converting bad input to a 4xx error.
Wrap type conversion in a try/except and return a JsonResponse with status 400:
try:
min_year = int(request.GET['min_year']) if 'min_year' in request.GET else None
except ValueError:
return JsonResponse({'error': 'min_year must be an integer'}, status=400)
This turns the 500 into a 400, which is what the test expects.
Common Mistakes
- Fixing the symptom in the test fixture instead of the application code
- Applying
.distinct()only to the last filter instead of the final queryset - Forgetting to re-run the full suite after each fix — a fix for one test can break another
- Spending more than 10 minutes on any single failure before moving on; come back with fresh eyes
Time Management (60-minute window)
| Phase | Time |
|---|---|
| Run suite, read all failures, group them | 5 min |
| Fix 500s | 10 min |
| Fix routing/parameter extraction | 10 min |
Fix queryset filters and .distinct() | 20 min |
| Fix ordering and tie-breakers | 10 min |
| Final full suite run, review any remaining failures | 5 min |