在 Django Rest Framework 中使用 class APIView 进行分页

PAGINATION using class APIView in Django Rest Framework

我已经尝试对我的数据进行分页..但这不起作用,我仍然从数据库中获取所有数据 这是 views.py :

class User_apiView(APIView):
    pagination_class=PageNumberPagination
    def get(self, request):
        user = User.objects.all() 
        # pagination_class=PageNumberPagination
        serializer = TripSerializer(user, many = True)
        return Response(serializer.data)

这是 settings.py :

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 2,
}

这是我在此 url http://127.0.0.1:8000/api/users/?PAGE=4&PAGE_SIZE=1

中收到的数据


HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 115,
        "is_normaluser": null,
        "is_agency": null,
        "last_login": "2022-02-11T20:28:13.506519Z",
        "is_superuser": true,
        "first_name": "qaz",
    },
    {
        "id": 115,
        "is_normaluser": null,
        "is_agency": null,
        "last_login": "2022-02-11T20:28:13.506519Z",
        "is_superuser": true,
        "first_name": "qaz",
    },
    {
        "id": 115,
        "is_normaluser": null,
        "is_agency": null,
        "last_login": "2022-02-11T20:28:13.506519Z",
        "is_superuser": true,
        "first_name": "qaz",
    },
   
]

分页等仅适用于已实现分页逻辑的 APIView,例如 ListAPIView。您可以使用:

from rest_framework.generics import <strong>ListAPIView</strong>

class User_apiView(<strong>ListAPIView</strong>):
    pagination_class = PageNumberPagination
    queryset = User.objects.all()
    serializer_class = TripSerializer

这将实现 .get(…) 获取分页查询集的方法,并使用序列化程序序列化数据并将其放入响应中。