user2492364
user2492364

Reputation: 6693

Using django-filter to filter by a single date

I am trying to filter time ranges (like '2014-12-27' < time <= '2014-12-28') using only one parameter.

I currently use a url like this for getting a single day

http://127.0.0.1:8000/movieapi/movieshowtime/?mixtime=2014-12-27&maxtime=2014-12-28

I would like to be able to do something like this

http://127.0.0.1:8000/movieapi/movieshowtime/?timerange=2014-12-27 

But it does not work. The filterset that I am currently using is

class MovieShowtimeFilter(django_filters.FilterSet):
    mixtime = django_filters.DateTimeFilter(name="movietime",lookup_type='gte')
    maxtime = django_filters.DateTimeFilter(name="movietime",lookup_type='lt')
    timerange = django_filters.DateRangeFilter(name='movietime')

    class Meta:
        model = MovieShowtime
        fields = ['mixtime','maxtime','timerange']

Upvotes: 2

Views: 1280

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41671

The DateRangeFilter provided by django-filter allows you to filter across common date ranges like "today", "the past week", "last month", etc. It does not allow you to filter a queryset down to a specific date.

You should be able to do this with a custom filter though.

from django_filters.filters import DateFilter

class WithinDateFilter(DateFilter):

    def filter(self, qs, value):
        from datetime import timedelta

        if value:
            date_value = value.replace(hour=0, minute=0, second=0)

            filter_lookups = {
                "%s__range" % (self.name, ): (
                    value,
                    value + timedelta(days=1),
                ),
            }

            qs = qs.filter(**filter_lookups)

        return qs

This should allow you to pass in the single date through the url, and have the query be filtered to only times within that specific date.

class MovieShowtimeFilter(django_filters.FilterSet):
    timerange = WithinDateFilter(name='movietime')

    class Meta:
        model = MovieShowtime
        fields = ['mixtime','maxtime','timerange']

Upvotes: 4

Related Questions