无法使用DateTimeFilter进行过滤,而是返回所有结果

时间:2015-04-29 00:02:37

标签: django django-rest-framework django-filter

我试图实施一个基本的"在" /"在"之后开始?过滤我的一个模特。不幸的是,过滤器永远不会被应用。我做错了什么?

模型

class Shift(models.Model):
    ...snip...
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    ...snip...

    class Meta:
        ordering = ('station', 'employee', 'confirmed', 'start_time',)

FilterSet

import django_filters
from serverapp.models import Shift


class ShiftFilter(django_filters.FilterSet):
    """
    A filter to enable fetching shifts within a date range
    """
    # Specify the URL parameters we can use for filtering
    start_before = django_filters.DateTimeFilter(
        name="start_time",
        lookup_type="lte")
    start_after = django_filters.DateTimeFilter(
        name="start_time",
        lookup_type="gte")

    class Meta:
        # Specify the mode we're filtering on
        model = Shift
        # Specify the fields you can filter by (in this case just the
        # two above)
        fields = ['start_before', 'start_after']

查看

class ShiftViewSet(viewsets.ModelViewSet):
    serializer_class = ShiftSerializer
    filter_class = ShiftFilter
    ...snip...

查询(使用HTTPIE)

http http://127.0.0.1:8000/v1/shifts/?start_before=2015-04-23
http http://127.0.0.1:8000/v1/shifts/?start_after=2015-04-23

记录

id  start_time              end_time 
13  2015-04-16 16:18:13     2015-04-17 16:18:13
14  2015-04-16 16:18:13     2015-04-17 16:18:13
15  2015-04-24 16:18:13     2015-04-24 17:18:13

我希望start_before=2015-04-23返回2015年4月16日的两条记录,并start_after=2015-04-23返回2015年4月24日的一条记录。不幸的是,无论我运行哪两个查询,我都会收回所有三个记录。

这实现起来似乎很简单,我怎么能搞砸了?

1 个答案:

答案 0 :(得分:1)

如果您想使用 String str = "This is a string."; String[] array = str; ,请将django_filters添加到filters.DjangoFilterBackend

对于GLOBAL:

settings.py

filter_backends

具体观点:

REST_FRAMEWORK = {
    #...
    # !!! it's a list or tuple !!!
    # of course, you can add other backends
    "DEFAULT_FILTER_BACKENDS": ( 
        'rest_framework.filters.DjangoFilterBackend',
    )
    #...
}