Django - How to filter by date with Django Rest Framework? Django - How to filter by date with Django Rest Framework? django django

Django - How to filter by date with Django Rest Framework?


To expand on Flaiming's answer, if you're only ever going to be filtering via ISO datetime formats, it helps to overwrite the defaults to always use the IsoDateTimeFilter. This can be done per filterset with e.g.

from django.db import models as django_modelsimport django_filtersfrom rest_framework import filtersfrom rest_framework import viewsetsclass EventFilter(filters.FilterSet):    class Meta:        model = Event        fields = {            'timestamp': ('lte', 'gte')        }    filter_overrides = {        django_models.DateTimeField: {            'filter_class': django_filters.IsoDateTimeFilter        },    }class EventsView(viewsets.ReadOnlyModelViewSet):    ...    filter_class = EventFilter

You then won't have to worry about setting a different filter for each lookup expression and each field.


You can create specific FilterSet as follows:

import django_filtersfrom rest_framework import filtersfrom rest_framework import viewsetsclass EventFilter(filters.FilterSet):    timestamp_gte = django_filters.DateTimeFilter(field_name="timestamp", lookup_expr='gte')    class Meta:        model = Event        fields = ['event_type', 'event_model', 'timestamp', 'timestamp_gte']class EventsView(viewsets.ReadOnlyModelViewSet):    ...    filter_class = EventFilter

Than you can filter by "/api/v1/events/?timestamp_gte=2016-01-02"

EDIT: Just to clarify, this example uses django-filter library.


IsoDateTimeFilter is very picky about the input format; instead of:

  • 2016-01-02 00:00+0000

use:

  • 2016-01-02T00:00:00Z