---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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 `"/admin/newsroom/story/?status__exact=published&q=bridge"`, `ModelAdmin.changelist_view` (`django/contrib/admin/options.py:ModelAdmin.changelist_view`) delegates all query-string parsing, filtering, searching, sorting, `select_related` optimization, and pagination to a per-request helper class: **`ChangeList`** (`django/contrib/admin/views/main.py:ChangeList`).

## How `ChangeList.get_queryset` builds the SQL pipeline

Inside `ChangeList.__init__` (`django/contrib/admin/views/main.py:ChangeList.__init__`), Django calls `ChangeList.get_queryset` (`django/contrib/admin/views/main.py:ChangeList.get_queryset`) followed immediately by `ChangeList.get_results` (`django/contrib/admin/views/main.py:ChangeList.get_results`). Trace the exact six stages inside `get_queryset`:

1. **Allow-list check via `ChangeList.get_filters` (`django/contrib/admin/views/main.py:ChangeList.get_filters`):** Every query-string parameter not in `IGNORED_PARAMS` (`"p"`, `"o"`, `"q"`, `"all"`, `"_facets"`, etc.) must pass `BaseModelAdmin.lookup_allowed` (`django/contrib/admin/options.py:BaseModelAdmin.lookup_allowed`), raising `DisallowedModelAdminLookup` if an attacker tries to probe arbitrary related fields like `?reporter__user__password__startswith=pbkdf2`!
2. **Sidebar filters & remaining lookups:** Each declared `"list_filter"` builds a `FieldListFilter` (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 a `Q` filter.
3. **Auto `select_related` via `ChangeList.apply_select_related` (`django/contrib/admin/views/main.py:ChangeList.apply_select_related`):** Only runs if `"not qs.query.select_related"` (meaning your `BaseModelAdmin.get_queryset` did not already call `QuerySet.select_related`!). Notice two crucial details in Django `6.1`:
   - `ModelAdmin.__init_subclass__` (`django/contrib/admin/options.py:ModelAdmin.__init_subclass__`) now **deprecates** setting `"list_select_related = True"` (`RemovedInDjango2028Warning`), because unbounded `QuerySet.select_related` joins every non-null `ForeignKey` on the model unnecessarily. Always set either `False` or an explicit tuple of relation names!
   - When `"list_select_related = False"` (the default), `ChangeList.get_select_related_fields` (`django/contrib/admin/views/main.py:ChangeList.get_select_related_fields`) inspects every name in `"list_display"` via `"self.lookup_opts.get_field(field_name)"`. Every direct `ForeignKey` (`ManyToOneRel`) field listed in `"list_display"` — like `"desk"`, `"reporter"`, and `"edition"` on `"desk/"`'s `"StoryAdmin"` — is joined automatically!
4. **Deterministic ordering via `ChangeList.get_ordering` (`django/contrib/admin/views/main.py:ChangeList.get_ordering`):** Parses `"?o=..."` column indices, merges `BaseModelAdmin.ordering` / `"Meta.ordering"`, and appends `"-pk"` if `"queryset.order_by(*ordering).totally_ordered"` is `False` so pagination never duplicates or skips rows across page boundaries!
5. **Keyword search via `ModelAdmin.get_search_results` (`django/contrib/admin/options.py:ModelAdmin.get_search_results`):** Splits `"?q=..."` with `smart_split` (preserving quoted phrases!), builds OR-ed `"__icontains"` (or `"^"` `"istartswith"`, `"="` `"iexact"`, `"@"` `"search"`) lookups across `"search_fields"`, and ANDs each search term together.
6. **Duplicate guard:** If any filter or search field crossed a multi-valued relation (`lookup_spawns_duplicates`), Django appends `QuerySet.distinct` automatically so a `"Story"` with two `"StoryBeat"` rows does not appear twice in the table!

Finally, `ChangeList.get_results` runs pagination. Notice lines 302–311 of `django/contrib/admin/views/main.py`: by default (`show_full_result_count = True`), `ChangeList` runs **two `"COUNT(*)"` queries** — `"paginator.count"` on the filtered queryset AND `"self.root_queryset.count()"` 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.get_select_related_fields`): Django's automatic `select_related` ONLY inspects concrete model field names that `"lookup_opts.get_field(field_name)"` can find!

The instant a developer replaces `"desk"`, `"reporter"`, and `"edition"` in `"StoryAdmin.list_display"` with a formatted `"byline"` method — `f"{obj.reporter.name} ({obj.desk.section_code} · {obj.edition.slug})"` — `"lookup_opts.get_field('byline')"` 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`!

```text figure=admin-changelist-and-changeform
Admin _changeform_view atomic POST sequence & ChangeList N+1 benchmark on desk/ (Django 6.1.3)

1. ModelAdmin._changeform_view atomic POST (Story + CorrectionInline -> 26 SQL):
   transaction.atomic() -> ModelForm.is_valid() + all_valid(formsets)
   -> save_form(commit=False) + save_model() [UPDATE newsroom_story]
   -> save_related() [save_m2m() + INSERT newsroom_correction]
   -> LogEntry [INSERT django_admin_log, JSON diff] -> HTTP 302 redirect

2. StoryAdmin ChangeList over 25 stories (7 trials, median ms):
   callable list_display (N+1 storm)            80 SQL  33.98 ms  (1.00x baseline)
   default StoryAdmin (auto select_related)      5 SQL  14.86 ms  (2.29x faster)
   callable + list_select_related                5 SQL  13.79 ms  (2.46x faster)
   callable + select_related + no full count     4 SQL  13.94 ms  (2.44x faster)
```

*Every SQL count, atomic write operation, and millisecond bar is parsed directly from `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/"`:

```text recording=ch11-auth
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
```

```text recording=ch11-bench
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.db.transaction.atomic`, and structured JSON `LogEntry` auditing in one single `POST`. We finish Chapter 11 in [changeform_view, inlines, and audit logging](changeform.md).
