Loading

drf——基于apiview写过滤、排序和分页

基于APIView带过滤和排序

from rest_framework.views import APIView
from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response

class BookView(APIView):
    # /books/?ordering=-price&name=红楼梦
    def get(self,request):
        ordering = request.query_params.get('ordering')
        name = request.query_params.get('name')
        book_list = Book.objects.all()
        if ordering:
            book_list = book_list.order_by(ordering)
        if name:
            book_list = book_list.filter(name__contains=name)
        ser = BookSerializer(instance=book_list,many=True)
        return Response(ser.data)

基于APIView带过滤、排序和分页

from rest_framework.views import APIView
from .models import Book
from .serializer import BookSerializer
from rest_framework.response import Response
from .page import MyPageNumberPagination

class BookView(APIView):
    def get(self,request):
        ordering = request.query_params.get('ordering')
        name = request.query_params.get('name')
        book_list = Book.objects.all()
        if ordering:
            book_list = book_list.order_by(ordering)
        if name:
            book_list = book_list.filter(name__contains=name)
        # 加入分页
        pagination = MyPageNumberPagination()  # 自己写的分页类实例化得到对象
        page = pagination.paginate_queryset(book_list, request, self)
        ser = BookSerializer(instance=page,many=True)
        # return pagination.get_paginated_response(ser.data)
        return Response({
            'code':100,
            'msg':'成功',
            'count':pagination.page.paginator.count,
            'next':pagination.get_next_link(),
            'previous':pagination.get_previous_link(),
            'results':ser.data
        })
"""
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin

根据源码写自己的分页
根据ListModelMixin中的page = self.paginate_queryset(queryset)
分页类的对象调用

paginate_queryset是GenericAPIView中的
---->>>paginate_queryset(queryset, self.request, view=self)
再给分类的对象进行序列化 序列化之后return 视图类的对象调用get_paginated_response(serializer.data)
---》会去GenericAPIView中找 最后返回分页类的对象调用get_paginated_response(data)


所以可以在自己写的视图类下 先实例化出一个对象 去调用paginate_queryset
如果返回值不为空则进行序列化
if page is not None:
    # 把page进行了序列化
   serializer = self.get_serializer(page, many=True)
   # 序列化完之后return 分页类的对象调用 get_paginated_response(serializer.data)方法 继承的分页类中的方法
   return self.get_paginated_response(serializer.data)
 
get_paginated_response(serializer.data)即--->>>
return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ]))
"""
posted @ 2023-05-26 16:56  抱紧小洪  阅读(85)  评论(0编辑  收藏  举报