Home > database >  PAGINATION using class APIView in Django Rest Framework
PAGINATION using class APIView in Django Rest Framework

Time:04-04

I have try to paginate my data.. but this is not work , I'm still getting all data from DataBase this is 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)

this is settings.py :

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

this the data I recieve in this 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",
    },
   
]

CodePudding user response:

Pagination, etc. only works for APIViews that have implemented the logic for pagination, for example a ListAPIView. You this can work with:

from rest_framework.generics import ListAPIView

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

This will implement the .get(…) method that will fetch the paginated queryset, and use the serializer to serialize the data and put it into a response.

  • Related