4👍
ModelAdmin list_filter accepts either fields or a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods. In this case you could take the second option and do something like:
class ItemCountListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the
# right admin sidebar just above the filter options.
title = 'item count'
# Parameter for the filter that will be used in the URL query.
parameter_name = 'count'
def lookups(self, request, model_admin):
"""
Returns a list of tuples. The first element in each
tuple is the coded value for the option that will
appear in the URL query. The second element is the
human-readable name for the option that will appear
in the right sidebar.
"""
max_value = Sale.objects.all().annotate(
count_items=Count('sales_det')
).aggregate(max_value=Max('count_items'))['max_value']
return [(i, i) for i in range(0, max_value)]
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
# Compare the requested value (either '80s' or '90s')
# to decide how to filter the queryset.
return queryset.annotate(
count_items=Count('sales_det')
).filter(
count_items=self.value()
)
class SaleAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'customer', 'get_itens', 'get_total')
readonly_fields = ['get_total']
list_filter = ('customer', ItemCountListFilter)
admin.site.register(Sale, SaleAdmin)
Source:stackexchange.com