使用Django Rest Framework过滤DateTimeField

时间:2014-07-17 14:04:33

标签: django django-rest-framework

我有一个带有DateTimeField的模型:

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

我使用Django Rest Framework将api链接到它:

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

当我使用以下网址点击我的API时,它可以完美运行:

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

但是,我希望通过基于日期和时间过滤来做更多事情。我尝试了以下网址但没有成功:

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

如果你们知道如何继续......我在django-filters文档中找不到任何好的信息或示例......

3 个答案:

答案 0 :(得分:2)

这可能不是你想要的,但你可以简单地从Unix时间转换。 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']

答案 1 :(得分:2)

更简单的解决方案,如果您不关心几分之一秒:用空格替换“T”(%20):

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

为我工作。

答案 2 :(得分:1)

此问题和解决方案记录在此DRF问题页面中:https://github.com/tomchristie/django-rest-framework/issues/1338

TL; DR:Django ISO转换'问题'阻止DRF按预期工作。已在DRF中编写了此修复程序,您可以使用IsoDateTimeField代替DateTimeField。只需在请求参数值中使用空格重播T也可以。