11.6 Sessions, auth, and the admin
Inside ChangeList: filters, search, and queries
How does ChangeList translate admin query-string parameters into filters, search clauses, ordering, and pagination — and why can one careless list_display callable turn an admin page into an N+1 storm?
When an editor opens "/, ModelAdmin delegates all query-string parsing, filtering, searching, sorting, select_related optimization, and pagination to a per-request helper class: ChangeList.
How ChangeList.get_queryset builds the SQL pipeline
Inside ChangeList, Django calls ChangeList followed immediately by ChangeList. Trace the exact six stages inside get_queryset:
- Allow-list check via
ChangeList: Every query-string parameter not in.get_filters IGNORED_PARAMS("p","o","q","all","_facets", etc.) must passBaseModelAdmin, raising.lookup_allowed DisallowedModelAdminLookupif an attacker tries to probe arbitrary related fields like?reporter__user__password__startswith=pbkdf2! - Sidebar filters & remaining lookups: Each declared
"list_filter"builds aFieldListFilter(consuming its own query parameters and narrowing the queryset),"date_hierarchy"converts year/month/day parameters into index-friendly"__gte"/"__lt"range bounds, and any remaining allowed lookup parameters are combined into aQfilter. - Auto
select_relatedviaChangeList: Only runs if.apply_select_related "not qs(meaning your.query .select_related" BaseModelAdmindid not already call.get_queryset QuerySet!). Notice two crucial details in Django.select_related 6.1:ModelAdminnow deprecates setting.__init_subclass__ "list_select_related = True"(RemovedInDjango2028Warning), because unboundedQuerySetjoins every non-null.select_related ForeignKeyon the model unnecessarily. Always set eitherFalseor an explicit tuple of relation names!- When
"list_select_related = False"(the default),ChangeListinspects every name in.get_select_related_fields "list_display"via"self. Every direct.lookup_opts .get_field(field_name)" ForeignKey(ManyToOneRel) field listed in"list_display"— like"desk","reporter", and"edition"on"desk/"'s"StoryAdmin"— is joined automatically!
- Deterministic ordering via
ChangeList: Parses.get_ordering "?o=..."column indices, mergesBaseModelAdmin/.ordering "Meta.ordering", and appends"-pk"if"querysetis.order_by(*ordering).totally_ordered" Falseso pagination never duplicates or skips rows across page boundaries! - Keyword search via
ModelAdmin: Splits.get_search_results "?q=..."withsmart_split(preserving quoted phrases!), builds OR-ed"__icontains"(or"^""istartswith","=""iexact","@""search") lookups across"search_fields", and ANDs each search term together. - Duplicate guard: If any filter or search field crossed a multi-valued relation (
lookup_spawns_duplicates), Django appendsQuerySetautomatically so a.distinct "Story"with two"StoryBeat"rows does not appear twice in the table!
Finally, ChangeList runs pagination. Notice lines 302–311 of django/: by default (show_full_result_count = True), ChangeList runs two "COUNT(*)" queries — "paginator on the filtered queryset AND "self on the unfiltered table just to print "1 result (25 total)"! On a 50-million-row Postgres table, setting "show_full_result_count = False" (and overriding paginator when needed) removes an entire full-table count scan from every filtered admin page load!
Why one list_display callable triggers an N+1 storm
Now look back at step 3 (ChangeList): Django’s automatic select_related ONLY inspects concrete model field names that "lookup_opts can find!
The instant a developer replaces "desk", "reporter", and "edition" in "StoryAdmin with a formatted "byline" method — f"{obj — "lookup_opts raises FieldDoesNotExist, get_select_related_fields() returns [], and every single row rendered in the HTML table fires 3 lazy foreign-key "SELECT"s (3 × 25 = 75 extra SQL queries on a 25-story page, or 300 extra queries on the default 100-row admin page!). Adding a single line — list_select_related = ("desk", "reporter", "edition") — collapses all 80 queries straight back down to 5!
ch11-auth and ch11-bench. Notice that even on zero-latency in-memory SQLite, eliminating 75 N+1 queries speeds up rendering 25 rows by 2.46x (33.98 ms -> 13.79 ms ); across a real network database where each round trip costs 0.5–2 ms, 75 extra queries add 38–150 ms of pure idle wait to every admin click!Watch all four "StoryAdmin" configurations — plus a filtered search "?status__exact=published&q=bridge" — measured live on "desk/":
6. ChangeList auto-select_related vs custom callable N+1
default_StoryAdmin (25 stories): sql=5 auto_select_related=['desk', 'reporter', 'edition']
callable_no_select (25 stories): sql=80 auto_select_related=[] (N+1 storm!)
callable_list_select_related: sql=5 no_full_result_count_sql=4
filtered_search (?status__exact=published&q=bridge): rows=1 sql=5
2. StoryAdmin ChangeList render over 25 stories (7 trials, ms/render)
changelist_config sql median_ms speedup
callable list_display (N+1 storm) 80 33.98 1.00x
default StoryAdmin (auto select_related) 5 14.86 2.29x
callable + list_select_related 5 13.79 2.46x
callable + select_related + no full count 4 13.94 2.44x
Click any story in that changelist and you land on the Admin’s edit form — where ModelAdmin coordinates a parent ModelForm, two InlineModelAdmin formsets, django, and structured JSON LogEntry auditing in one single POST. We finish Chapter 11 in changeform_view, inlines, and audit logging.