Reputation: 515
I have some json data from 3rd party API which has parameters like 3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber1
NumberOfItemsOnPage - how many items will be on one page and PageNumber - current page. This json has items, info about current page, how many items on page and how many pages in general
And I want to know how can I paginate through that json using paginate_by in class ListView
class myView(ListView)
paginate_by = 5
def get_queryset(self, ...):
queryset = []
page_number = self.request.GET.get('page')
# This might be wrong but I doesn't realy care because I need to know how to paginate using default django pagination
request = f'3rd_party.com/API?NumberOfItemsOnPage=5&PageNumber{page_number}'
queryset = request.json()
return queryset
I guess I need to override django Paginator class but I dont know how to do that because django paginator paginate will through only first page and won't get another's
Upvotes: 0
Views: 135
Reputation: 853
Here you will find the official documentation: how to override pagination
For my part, I follow the Style Guide of HackSoftware:
For this you need to create your function get_paginated_response
:
from rest_framework.response import Response
def get_paginated_response(*, pagination_class, serializer_class, queryset, request, view):
paginator = pagination_class()
page = paginator.paginate_queryset(queryset, request, view=view)
if page is not None:
serializer = serializer_class(page, many=True)
return paginator.get_paginated_response(serializer.data)
serializer = serializer_class(queryset, many=True)
return Response(data=serializer.data)
and call it like that:
class UserListApi(ApiErrorsMixin, APIView):
class Pagination(LimitOffsetPagination):
default_limit = 1
class OutputSerializer(serializers.Serializer):
id = serializers.CharField()
email = serializers.CharField()
is_admin = serializers.BooleanField()
def get(self, request):
users = user_list()
return get_paginated_response(
pagination_class=self.Pagination,
serializer_class=self.OutputSerializer,
queryset=users,
request=request,
view=self
)
Upvotes: 0