基于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
根据源码写自己的分页
配置的分页类的对象调用了page = self.paginate_queryset(queryset)
paginate_queryset是GenericAPIView中的
---->>>paginate_queryset(queryset, self.request, view=self)
所以可以在自己写的视图类下 先实例化出一个对象 去调用paginate_queryset
如果返回值不为空则进行序列化
if page is not None:
# 把page进行了序列化
serializer = self.get_serializer(page, many=True)
# 实例化完之后调用get_paginated_response方法 继承的分页类中的方法
return self.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)
]))
"""
标签:name,get,apiview,self,list,book,import,排序,drf
From: https://www.cnblogs.com/XxMa/p/17435242.html