django-rest-framework filter by date=None

tobygriffin picture tobygriffin · Feb 3, 2014 · Viewed 8.4k times · Source

I am using django-rest-framework with django-filter. I need to retrieve a list of Widgets where the date property is None, but no matter what query I have tried, I am getting either empty responses or full, unfiltered responses.

Here's how I have defined the viewset and filterset.

class WidgetFilter(django_filters.FilterSet):
    date = django_filters.DateTimeFilter(name='date', lookup_type='exact')
    no_date = django_filters.DateTimefilter(name='date', lookup_type='isnull')
    class Meta:
        model = Widget
        fields = ['date',]

class WidgetSet(viewsets.ModelViewSet):
    model = Widget
    filter_class = WidgetFilter

The following queries result in empty [] responses:

?date=None
?date=0
?date=NULL
?date=False
?date=2012-05-24T11:20:06Z  # a known and correct date

The following queries result in all objects being returned:

?date=
?no_date=True
?no_date=False
?no_date=1
?no_date=0

Any help is very much appreciated! I have been unable to find any information on using dates (or passing None as a filter value) with django-filter specifically via django-rest-framework.


In case there is no more elegant way, here is how I bodged my workaround, but I'd still like to know of a solution that uses django-filter, if one exists.

class WidgetSet(viewsets.ModelViewSet):
    model = Widget

    def get_queryset(self):
        if 'no_date' in self.request.QUERY_PARAMS:
            return self.model.objects.filter(date=None)
        return self.model.objects.all()

Answer

Matmas picture Matmas · Jul 27, 2015

Specifying isnull directly in the filter's name argument as 'date__isnull' seems to be working for me with Django REST Framework 3.1.3.

class WidgetFilter(django_filters.FilterSet):
    date = django_filters.DateTimeFilter(name='date')
    no_date = django_filters.BooleanFilter(name='date__isnull')
    class Meta:
        model = Widget
        fields = []