Search code examples
django-rest-frameworkdjango-filter

Django DRF DateFilter: filtering dates by months


I'm trying to add date filters on a Django DRF viewset

models.py:

class Day(models.Model):
    date = models.DateField(unique=True)
    ...

In the views, I added a filterset as follow:

class DateFilter(filters.FilterSet):
    month = filters.DateFilter(field_name='date__month', lookup_expr='exact')

    class Meta:
        model = Day
        fields = ['month']

I tried to define the month filter also as follow with the same error:

month = filters.DateFilter(field_name='date', lookup_expr='month')

And added in the viewset:

class DayViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = Day.objects.all().order_by('-date')
    serializer_class = DaySummarySerializer
    lookup_field = 'slug'
    filter_backends = [filters.DjangoFilterBackend]
    filterset_class = DateFilter 

The filter appears in the rest framework page as intended but doesn't accept the month to be passed as an integer and return the following error.

I understand that a workaround is possible with adding these filters directly in the queryset but would it be possible to implement such filters with the django-filters library?

Filter

Error


Solution

  • Actually I managed to find the issue. Despite the fact that the filter applies to a date field, the correct filter to use, when filtering for a month or in general for a date part, is to use a NumberFilter.

    It turns out that both expression below work:

    date_month = filters.NumberFilter(field_name='date__month', lookup_expr='exact')
    date_month = filters.NumberFilter(field_name='date', lookup_expr='month')