在Django API视图中创建自定义搜索过滤器

时间:2019-03-25 07:28:46

标签: python django

我有我的自定义API视图,我想在此视图中使用“搜索”过滤器,但是通用过滤器不起作用,因此我想创建自定义视图,但它不起作用,而且我不知道问题出在哪里。

视图

class TaskIndexAPIView(APIView):
filter_backends = (CustomSearchFilter,)
search_fields = ('name', 'description', 'user__username')
def get_queryset(self):
    return Task.objects.all()

def get(self, request):
    tasks = self.get_queryset()
    for i in tasks:
        if i.date <= date.today():
            i.delayed = 'This task is delayed'
            i.save()
        else:
            i.delayed = ''
            i.save()

    serializer = IndexSerializer(tasks, many=True)
    return Response(serializer.data)

我的自定义搜索过滤器

search_filter

class CustomSearchFilter(filters.SearchFilter):
def get_search_fields(self, view, request):
    if request.get_queryset.get('name', 'user'):
        return ['name', 'user']
    return super(CustomSearchFilter, self).get_search_fields(view, request)

1 个答案:

答案 0 :(得分:1)

在您的上下文中, APIView generic view 之间的区别在于,通用视图具有一种称为 {{1 }} 来处理过滤和搜索操作。

所以在您看来,我们需要添加相同的内容。

filter_queryset()

您将获得过滤后的查询集为

class TaskIndexAPIView(APIView):
    filter_backends = (CustomSearchFilter,)
    search_fields = ('name', 'description', 'user__username')

    def filter_queryset(self, queryset):
        """
        Given a queryset, filter it with whichever filter backend is in use.
        You are unlikely to want to override this method, although you may need
        to call it either from a list view, or from a custom `get_object`
        method if you want to apply the configured filtering backend to the
        default queryset.
        """
        for backend in list(self.filter_backends):
            queryset = backend().filter_queryset(self.request, queryset, self)
        return queryset

    def get_queryset(self):
        return Task.objects.all()

    def get(self, request):
        the_filtered_qs = self.filter_queryset(self.get_queryset())

        tasks = the_filtered_qs
        for i in tasks:
            if i.date <= date.today():
                i.delayed = 'This task is delayed'
                i.save()
            else:
                i.delayed = ''
                i.save()

        serializer = IndexSerializer(tasks, many=True)
        return Response(serializer.data)