Last active
November 16, 2016 19:39
-
-
Save guillaumepiot/34e178ff439c5132f019 to your computer and use it in GitHub Desktop.
DJANGO CookBook - Custom list filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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,] | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How can I display the count of records in front of each filter?
i.e display in list filter
Paid(5),
Unpaid(10)
Thanks