django rest framework实现分页功能
在web开发中很多需求都需要实现分页功能,然而 Django Rest Framework 自带的分页功能,只能在 mixins.ListModelMixin and generics.GenericAPIView classes
继承这两个类才可以使用,而我们通常为了灵活性,往往会继承APIView
来实现,那么我们就需要自已使用分页功能。
一.serializers.py文件中定义序列化类
from rest_framework.serializers import Serializer
from models import MyModel
class MySerializer( Serializer.ModelSerializers): class Meta: model = MyModel fields = ("user_name", "age")
二.views.py视图函数中
from rest_framework.views import APIView
from rest_framework from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.core.paginator import Paginator
from serializers import MySerializer from models import MyModel @api_view(["GET"]) def get_list(request): try: page_size = int(request.GET.get('page_size', 2)) page = int(request.GET.get('page', 1)) except (TypeError, ValueError): return Response(status=status.HTTP_400_BAD_REQUEST) try: objs = MyModel.objects.all() except: return Response(status=status.HTTP_417_EXPECTATION_FAILED)
paginator = Paginator(objs, page_size) # paginator对象 total = paginator.num_pages #总页数 try: objs = paginator.page(page) except PageNotAnInteger: objs = paginator.page(1) except EmptyPage: objs = paginator.page(paginator.num_pages) serializer = MySerializer(objs, many=True) #序列化操作 return Response(data={ 'detail': serializer.data, page': page, 'total': total }, status=status.HTTP_200_OK) #返回
当我仰望星空, 看见了涛涛江水, 闻到了人声鼎沸;可当我蓦然回望,再也触摸不到那逝去的时光,再也看不到那夕阳下的少年!