如何在Django Rest Framework上使用普通Filter和SearchFilter?

时间:2016-11-04 08:15:05

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

我正在使用DRF(Django Rest Framework)。

我声明了一个ModelViewSet,现在我想在其上添加过滤器。

class GoodsViewSet(viewsets.ModelViewSet):
    class Filter(FilterSet):    
        class Meta:
            model = m.Goods

    filter_class = Filter
    filter_backends = (SearchFilter, Filter)
    search_fields = ['name',]
    queryset = m.Goods.objects.all()
    serializer_class = s.GoodsSerializer

看到我声明了一个Filter子类并将其应用于:

filter_class = Filter

在添加行之前,它在开始时起作用:

filter_backends = (SearchFilter, Filter)
search_fields = ['name',]

the doc告诉我们。

现在,在跳过普通filter_class时会应用搜索过滤器。

一句话,他们无法一起工作。

如何解决这个问题?

2 个答案:

答案 0 :(得分:18)

最后,我发现我们应该同时指定两个filter_backends

from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend

class GoodsViewSet(viewsets.ModelViewSet):
    class Filter(FilterSet):    
        class Meta:
            model = m.Goods

    filter_class = Filter
    filter_backends = (SearchFilter, DjangoFilterBackend)
    search_fields = ['name',]
    queryset = m.Goods.objects.all()
    serializer_class = s.GoodsSerializer

或者我们可以忽略特定filter_backends课程中的ViewSet字段,但会在settings.py中全局应用这些字段:

REST_FRAMEWORK = {
    # ... other configurations
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework.filters.SearchFilter',
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
}

这样,filter_classsearch_fields选项可以在ViewSet上同时使用。

答案 1 :(得分:1)

这对我有用:

    from django_filters import rest_framework as filters
    from django_filters.rest_framework import DjangoFilterBackend
    from rest_framework.filters import SearchFilter, OrderingFilter

-------- views.py -----------------------------

    filter_backends = (filters.DjangoFilterBackend, SearchFilter ,OrderingFilter)
    filter_fields =('completed',)
    ordering =('-date_created',)
    search_fields =('task_name',)