Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering on DateTimeField with Django Rest Framework

I have a model with a DateTimeField:

class MyShell(models):
    created = models.DateTimeField(auto_now=true)

I have an api linked to it using Django Rest Framework:

class ShellMessageFilter(django_filters.FilterSet):
    created = django_filters.DateTimeFilter(name="created",lookup_type="gte")

    class Meta:
        model = ShellMessage
        fields = ['created']


class ShellListViewSet(viewsets.ModelViewSet):
    """
        List all ShellMessages
    """
    serializer_class = ShellMessageSerializer
    queryset = ShellMessage.objects.all()
    filter_class = ShellMessageFilter

When I hit my API using the following URL it works perfectly:

http://127.0.0.1:8000/api/shell/?created=2014-07-17
# It returns all shell with a date greater than the one provided in URL

But, I want to do more than that by filtering base on a date and a time. I tried the following URL without success:

http://127.0.0.1:8000/api/shell/?created=2014-07-17T10:36:34.960Z
# It returns an empty array whereas there are items with a created field greater than 2014-07-17T10:36:34.960Z

If you guys know how to proceed... I don't find any good informations or example in django-filters documentation...

like image 957
Alex Grs Avatar asked Jul 17 '14 14:07

Alex Grs


2 Answers

Simpler solution if you don't care about fractions of seconds: replace the "T" with space (%20):

http://127.0.0.1:8000/api/shell/?created=2014-07-17%2010:36:34

Worked for me.

like image 127
Csaba Toth Avatar answered Sep 30 '22 20:09

Csaba Toth


This may not be what you want, but you could simply convert from Unix time. E.g.:

def filter_unix_dt(queryset, value):
    if not value:
        return queryset

    try:
        unix_time = int(value)
        t = datetime.fromtimestamp(unix_time)
        result = queryset.filter(created__gte=t)
        return result
    except ValueError:
        return queryset


class ShellMessageFilter(django_filters.FilterSet):
    created = django_filters.DateTimeFilter(action=filter_unix_dt)

    class Meta:
        model = ShellMessage
        fields = ['created']
like image 20
John R.B. Palmer Avatar answered Sep 30 '22 19:09

John R.B. Palmer