django 分页效果实现(djangorestframework内置以及django内置方法)

restframework的分页需要再setting 中添加一个

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 10
}
class UserInfoPage(generics.ListAPIView):
    queryset = UserInfo.objects.all()
    serializer_class = UserInfoSerializer
    def get(self, request, *args, **kwargs):
        pageObject = UserInfo.objects.all()
        page = self.paginate_queryset(pageObject)
        _total = self._paginator.count
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            _list = serializer.data
            return_dict = {
                'total': _total,
                'limit': 10,
                'list': _list
            }
            return Response(return_dict, status=status.HTTP_200_OK)

返回的效果图

django 分页效果实现(djangorestframework内置以及django内置方法)_第1张图片

下面是我自己写的一个分页方法 由于数据一多,返回json太费时间,就改成了上面的那种方式

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


def page_info(info, pageSize=10, pageNo=1):
    # info格式 为 数据序列化后的json格式
    p = Paginator(info, pageSize)
    try:
        contract = p.page(pageNo).object_list
    except PageNotAnInteger:
        contract = p.page(1).object_list
    except EmptyPage:
        contract = []
    something = {
        'pageNo': pageNo,
        'pageSize': pageSize,
        'list': contract,
        'total': p.count,
    }
    return something

你可能感兴趣的:(django)