[Django]-Custom Filter in Django Admin

5👍

Finally, I found the solution to my problem.

class CountryFilter(admin.SimpleListFilter):
    title = _('Country')
    parameter_name = 'country'

    def lookups(self, request, model_admin):
        countries = []
        qs = Country.objects.filter(id__in = model_admin.model.objects.all().values_list('country_id', flat = True).distinct())
        for c in qs:
            countries.append([c.id, c.name])
        return countries

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

Leave a comment