Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Last active November 16, 2016 19:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guillaumepiot/34e178ff439c5132f019 to your computer and use it in GitHub Desktop.
Save guillaumepiot/34e178ff439c5132f019 to your computer and use it in GitHub Desktop.
DJANGO CookBook - Custom list filter
# Tested in Django 1.6
# Import default list filter
from django.contrib.admin import SimpleListFilter
# Create the filter
class InvoicePaidFilter(SimpleListFilter):
title = _('Paid')
parameter_name = 'paid'
# Set the displaying options
def lookups(self, request, model_admin):
return (
('PAID', _('Paid')),
('UNPAID', _('Unpaid')),
)
# Assign a query for each option
def queryset(self, request, queryset):
if self.value() == 'PAID':
return queryset.filter(paid=True)
elif self.value() == 'UNPAID':
return queryset.exclude(paid=True)
# Assign the filter
class InvoiceAdmin(admin.ModelAdmin):
list_filter = [InvoicePaidFilter,]
...
@dariushazimi
Copy link

How can I display the count of records in front of each filter?
i.e display in list filter
Paid(5),
Unpaid(10)
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment