django.contrib.admin.filters SimpleListFilter Example Code

SimpleListFilter is a class within the Django project which can be subclasses to customize the Django admin's lookups and querying interface.

Understanding the following concepts are useful when coding projects that use Django's SimpleListFilter class:

You can also view the complete all topics page for even more resources.

Example 1 from AuditLog

Auditlog (project documentation) is a Django app that logs changes to Python objects, similar to the Django admin's logs but with more details and output formats. Auditlog's source code is provided as open source under the MIT license.

django-auditlog / src / auditlog /

from django.contrib.admin import SimpleListFilter

class ResourceTypeFilter(SimpleListFilter):
    title = 'Resource Type'
    parameter_name = 'resource_type'

    def lookups(self, request, model_admin):
        qs = model_admin.get_queryset(request)
        types = qs.values_list('content_type_id', 'content_type__model')
        return list(types.order_by('content_type__model').distinct())

    def queryset(self, request, queryset):
        if self.value() is None:
            return queryset
        return queryset.filter(content_type_id=self.value())

Sign up for a monthly email with Full Stack Python tutorials. No spam ever.

Learn More Python

Introduction to Ansible video course logo.

Deploy web apps with the Ansible configuration management tool.

Full Stack Python

Full Stack Python is an open book that explains concepts in plain language and provides helpful resources for those topics.
Updates via newsletter, Twitter & Facebook.

Matt Makai 2012-2019