Home » Django & REST Api » How to implement Pagination with Django & Django REST Framework ?

How to implement Pagination with Django & Django REST Framework ?

When you are working with lots of data like millions of object entries in the database, its just not possible to fetch complete JSON in one go which can content all the objects and parse to do any operations of the same. Hence to make the operations and user interface easier, Django provides pagination using which you can only fetch predefined set of objects in one page and when you click “Next” or “Previous” based on what you want to visit, you will get the next set of data.

Pagination makes data fetching simpler, so it can help for UI implementation with better performance.

Implementation of Pagination with Class based Views

High level pagination is not supported with class based views, hence we need to implement the necessary code using Django’s pagination class.

class user_by_userid(APIView):
    def get(self, request, user_id, format=None):
        users = UserInfo.objects.filter(userid=user_id)

        paginator = Paginator(users, 10)
        page = request.query_params.get('page')
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)

        serializer = UserInfoSerializer(users, many=True)
        return JsonResponse(serializer.data, safe=False)

As you can see above, most of the get code is similar to previous implementation of “get” function in class based views, the only addition to this code is,

        paginator = Paginator(users, 5)
        page = request.query_params.get('page')
        try:
            users = paginator.page(page)
        except PageNotAnInteger:
            users = paginator.page(1)
        except EmptyPage:
            users = paginator.page(paginator.num_pages)

Note: this pagination code must be before calling Serializers.

The JSON for first page can be accessed as, http://IP_ADDRESS:PORT/API_NAME/filter/?page=page_number example of this can be as, http://127.0.0.1:8000/user/my_userid/?page=1

Implementation of Pagination with ViewSets


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment