博客五部曲之三 - 博客RESTful


1269 浏览 5 years, 2 months

12 过滤

版权声明: 转载请注明出处 http://www.codingsoho.com/

过滤列表视图

这一节我们会讨论如何在列表里过滤,我们会和post_list函数一样用query来实现这个

重写PostListAPIView的get_queryset函数

class PostListAPIView(ListAPIView):
    # queryset = Post.objects.all()
    serializer_class = PostListSerializer
    def get_queryset(self, *args, **kwargs):
        # queryset_list = super(PostListAPIView, self).get_queryset(*args, **kwargs)
        queryset_list = Post.objects.all()
        query = self.request.GET.get("q")
        if query:
            queryset_list = queryset_list.filter(
                Q(title__icontains=query) |
                Q(content__icontains=query) | 
                Q(user__first_name__icontains=query) |
                Q(user__last_name__icontains=query)
                ).distinct()
        return queryset_list

类里面原来的queryset为Post.objects.all(),我们注释掉它,然后在get_queryset函数里实现它。

接着我们访问 http://127.0.0.1:8000/api/posts/?q=new ,搜索功能就实现了。

这个跟我们在djagno里的方法还是很一致的,RESTful提供了自己的一套方法

可以通过filter_backends来添加预定义的filter,包括搜索,排序等

from rest_framework.filters import (
    SearchFilter,
    OrderingFilter,
    )

class PostListAPIView(ListAPIView):
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['title', 'content', 'user__first_name']

搜索的关键字为search,排序的为ordering, 访问地址可以如下
http://127.0.0.1:8000/api/posts/? search=new%20post&ordering=-title

这个搜索跟我们刚刚前面的实现是不冲突的,是&的关系,如果我们希望搜索内容同时满足包含”update”和”new post”,可以用下面地址去获取
http://127.0.0.1:8000/api/posts/?q=update&search=new%20post

更多实现可以参考 http://www.django-rest-framework.org/api-guide/filtering/