Using ‘django-filter’ with CHOICES field – need “Any” option

djangodjango-filter

I'm using the very cool django-filter (via: http://github.com/alex/django-filter)
and either can't seem to wrap my head around the docs, or maybe just
need a little boost.

When I show the filter form on an object list page, for a FK field I
get the drop down that includes a "—–" which results in an
"any" type filter. But I have some choices set to a field on that
model, and I'd like to get the same "any" type option.
Here's a relevant example portion from models.py:

TICKET_STATUS_CHOICES = (
    ('new', 'New'),
    ('accepted', 'Accepted'),
    ('assigned', 'Assigned'),
    ('reopened', 'Reopened'),
    ('closed', 'Closed'),
)

class Ticket(models.Model):
    assigned_to = models.ForeignKey(User, null=True, blank=True)
    status = models.CharField(max_length=20,
choices=TICKET_STATUS_CHOICES, default='new')

import django_filters

class TicketFilter(django_filters.FilterSet):
    class Meta:
        model = Ticket
        fields = ['assigned_to', 'status']

When I display the filter form, 'assigned_to' gets an 'any' option, as
well as listing the available users. The 'status' field, however, is
limited to only the options listed in the actual '_CHOICES'.

How do I add an 'any' option to the fields based on _CHOICES?

Best Solution

DRY'er would be to use the already defined 'choices' argument for ChoiceFilter.

So you could simply extend your FILTER_CHOICES to be your TICKET_STATUS_CHOICES plus an 'any' option with the empty string:

FILTER_CHOICES = (
    ('new', 'New'),
    ('accepted', 'Accepted'),
    ('assigned', 'Assigned'),
    ('reopened', 'Reopened'),
    ('closed', 'Closed'),
    ('', 'Any'),
)

And your TicketFilter would be:

class TicketFilter(django_filters.FilterSet):

   status = django_filters.ChoiceFilter(choices=FILTER_CHOICES)

   class Meta:
      model = Ticket
      fields = ['assigned_to']
Related Question