Simple way to add counts to Django admin filter

Counts in Django admin filter

To add counts we need:

  1. Extend SimpleListFilter class
  2. Count all values inside of lookups method
  3. Return list of tuples with unique value and string title where you add a count form lookups

E.g. we have lang param in the model and want count MyModels with each unique language:

class MyModel(models.Model):
  lang = models.CharField(max_length=3, null=True, blank=True, default=None)

Create list filter class:

class BaseLangFilter(admin.SimpleListFilter):
    title = 'Language'
    parameter_name = 'lang'

    def lookups(self, request, model_admin):
        qs = model_admin.get_queryset(request)
        for lang in qs.values_list('lang', flat=True).distinct().order_by():
            count = qs.filter(lang=lang).count()
            if count:
                yield (lang, f'{lang} ({count})')

    def queryset(self, request, queryset):
        # Apply the filter selected, if any
        lang = self.value()
        if lang:
            return queryset.filter(lang=lang)

Class admin:

class ModeltAdmin(admin.ModelAdmin):
    list_filter = (BaseLanguageFilter, )

#django #python
Ivan Borshchov profile picture
Oct 11, 2020
by Ivan Borshchov
Did it help you?
Yes !

Best related

Other by Ivan Borshchov