[Django]-Creating Custom Filters for list_filter in Django Admin

88👍

You can indeed add custom filters to admin filters by extending SimpleListFilter. For instance, if you want to add a continent filter for ‘Africa’ to the country admin filter used above, you can do the following:

In admin.py:

from django.contrib.admin import SimpleListFilter

class CountryFilter(SimpleListFilter):
    title = 'country' # or use _('country') for translated title
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        countries = set([c.country for c in model_admin.model.objects.all()])
        return [(c.id, c.name) for c in countries] + [
          ('AFRICA', 'AFRICA - ALL')]

    def queryset(self, request, queryset):
        if self.value() == 'AFRICA':
            return queryset.filter(country__continent='Africa')
        if self.value():
            return queryset.filter(country__id__exact=self.value())

class CityAdmin(ModelAdmin):
    list_filter = (CountryFilter,)

9👍

Your list_display ,method returns a string, but if I understand correctly, what you want to do is add a filter which allows selection of countries of students, correct?

For this simple relation filter, and in fact for the “Student-Country” list display column as well, you don’t need to create a custom filter class, nor a custom list display method; this would suffice:

class MyAdmin(admin.ModelAdmin):
    list_display = ('country', )
    list_filter = ('country', )

The way django does list_filter, as explained in the docs, is first by automatically matching fields you provide to pre-built filter classes; these filters include CharField and ForeignKey.

list_display similarly automates the population of the changelist column using the field passed by retrieving the related objects and returning the unicode value of these (same as in the method you provided above).

5👍

In addition to Rick Westera answer, here is the Django Docs for this situation

ModelAdmin.list_filter
Set list_filter to activate filters in the right sidebar of the change list page of the admin
list_filter should be a list or tuple of elements

👤hasher

2👍

the lookup function is that show the exists values in admin;
in queryset function, self.value() is that was filtering by..

from django.contrib.admin import SimpleListFilter

class AllPriceFilter(admin.SimpleListFilter):

    title = 'All Price'
    parameter_name = 'All Price'

    def lookups(self, request, model_admin):
        return [(i.all_price, i.all_price) for i in model_admin.model.objects.all()]

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(all_price__lte=self.value())


class MyAdmin(admin.ModelAdmin):
    list_filter = (AllPriceFilter, ) 

Leave a comment