liveBook · Manning

List_filter

As explained in Django in Action

list_filter is a ModelAdmin configuration option specifying fields or filter classes that provide sidebar filters for a changelist.

list_filter adds filtering controls to the right side of a Django Admin changelist. Give it a model field for a straightforward filter, or provide a custom filter class when the available choices need more control. section 5.2.2

Choose the filter approach according to the field:

  • Use a BooleanField or a field restricted with choices when displaying every value is useful. section 5.2.2
  • Prefer search for wide-open fields such as last_name, because listing every database value can look messy and hurt performance. section 5.2.2
  • Customize DateField choices when defaults such as today, the last seven days, this month, and this year do not fit the data. section 5.2.2

Filtering musicians by birth decade

A custom filter extends admin.SimpleListFilter and supplies a title, a parameter_name, and two methods: class DecadeListFilter(admin.SimpleListFilter): title = 'decade born' parameter_name = 'decade' def lookups(self, request, model_admin): this_decade = (datetime.today().year // 10) * 10 return [ (str(year), f'{year}-{year + 9}') for year in range(this_decade - 10, this_decade - 100, -10) ] def queryset(self, request, queryset): start = self.value() if start is None: return queryset start = int(start) return queryset.filter( birth__gte=date(start, 1, 1), birth__lte=date(start + 9, 12, 31), ) lookups() names the sidebar choices. queryset() reads the selected value and restricts the changelist QuerySet; no selection leaves the original QuerySet unchanged. section 5.2.2

Figure 5.8 An overview of a custom list filter
figure

Use the overview to connect the filter’s displayed choices with the QuerySet operation that produces the filtered listing. section 5.2.2

How Django in Action covers it

How deep it goes
Defines simple field filters and custom SimpleListFilter choices and QuerySet logic, stopping short of broader admin configuration.
Examples
Uses BooleanField and choices fields, contrasts wide-open last_name filtering, and filters musician birthdays by decade.
What it assumes
Assumes familiarity with ModelAdmin fields and QuerySets while demonstrating custom filter classes from their essential methods.
What you can do after
Configure sidebar filters and implement custom choices that filter an admin QuerySet.
How it connects
Connects Django Admin ModelAdmin, changelists, search_fields, SimpleListFilter, and QuerySet filtering.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.