DRF必需的搜索过滤器

时间:2019-12-12 15:47:46

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

我的视图集效果很好

class PlayerViewSet(ModelViewSet):
     queryset = Player.objects.all()
     serializer_class = PlayerSerializer
     filter_backends = [SearchFilter]
     search_fields = ['nickname']

网址配置:

    path('player', PlayerViewSet.as_view({'get': 'list', 'post': 'create'})),

当我尝试使用诸如'player?search = randomNickname'之类的端点搜索对象时,一切正常

但是有可能发送不带搜索参数的GET请求,并且它会返回所有可能的对象

是否可以根据需要设置搜索字段?

1 个答案:

答案 0 :(得分:2)

由于ModelViewSet可以执行各种操作(获取,更新,删除..),因此最好扩展SearchFilter并使其在没有传递搜索参数或返回错误的情况下返回空结果。

from rest_framework import filters
from rest_framework.exceptions import ValidationError


class CustomSearchFilter(filters.SearchFilter):
    def filter_queryset(self, request, queryset, view):
        search_terms = self.get_search_terms(request)

        if not search_terms:
            # turn queryset in EmptyQuerySet
            # so no objects will be returned
            return queryset.none()

            # Alternatively, an error can be raise  
            #raise ValidationError(
            #    "%s parameter is required!" % self.search_param
            #)

        return super().filter_queryset(request, queryset, view)


class PlayerViewSet(ModelViewSet):
    queryset = Player.objects.all()
    serializer_class = PlayerSerializer
    filter_backends = [CustomSearchFilter]
    search_fields = ['nickname']