Loading

分页使用示例【drf后端分页】

1.代码

from rest_framework.pagination import PageNumberPagination

class UserModelSerializer(serializers.ModelSerializer):
    role_display = UserRoleSerializer(many=True, source='roles', read_only=True)

    class Meta:
        model = models.User
        fields = ["id", "username", 'password', "is_super", "roles", "role_display"]


class UserView(BaseView, ModelViewSet):
    authentication_classes = [JwtAuthentication]
    permission_classes = [RbacPermission]
    pagination_class = MinePageNumberPagination

    queryset = models.User.objects.all().order_by("-id")
    serializer_class = UserModelSerializer

    @action(detail=False, methods=['get'], url_path="role")
    def total_role(self, request):
        queryset = models.Role.objects.all()
        ser = UserRoleSerializer(instance=queryset, many=True)
        return Response(ser.data)

2.settings.py

REST_FRAMEWORK = {
    "UNAUTHENTICATED_USER": None,
    "UNAUTHENTICATED_TOKEN": None,
    "EXCEPTION_HANDLER": "utils.view.exception_handler",
    "PAGE_SIZE":10
}

3.utils/pagination.py

from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


class MinePageNumberPagination(PageNumberPagination):
    page_size_query_param = 'size'  # 允许通过查询参数指定每页条数
    max_page_size = 150

    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'page_size': self.request.query_params.get('size', self.page_size),
            'results': data,
        })


4.源码的

def get_paginated_response(self, data):
    return Response({
        'count': self.page.paginator.count,
        'next': self.get_next_link(),
        'previous': self.get_previous_link(),
        'results': data,
    })
posted @ 2024-10-05 23:07  一只大学生  阅读(4)  评论(0编辑  收藏  举报