I am using APIView
for get and post items.
I wanted to implement pagination for my API using Django Rest Framework, but it is not working.
I want to show 10 items per page but when I do api/v1/items?page=1
, I get all the items and if I just do api/v1/items
I get an empty list.
Here is what I have done:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
class ItemsAPIView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
"""
Return a list of all items of this user.
"""
reply = {}
page = request.GET.get('page')
print ('page is', page)
try:
products = BaseItem.objects.owned_items().filter(owner=request.user)
reply['data'] = OwnedItemSerializer(products, many=True).data
items = BaseItem.objects.filter(owner=request.user)
paginator = Paginator(items, 1)
items_with_pagination = paginator.page(page)
if page is not None:
reply['data'].extend(ItemSerializer(items_with_pagination, many=True).data)
reply['data'].extend(ItemSerializer(items, many=True).data)
paginator = None worked for me
You could make your life a lot easier and just use a ListView. By overriding render_to_response you can make it output json instead of HTML. It does all the pagination for you.
Non generic views and viewsets do not have pagination by default as stated in the django rest framework documentation:
I have composed a full example on enabling pagination on non generic views with code on how to achieve this:
For more details have a look at the example link provided.
extend
GenericAPIView
instead ofAPIView
and definepagination_class
inGenericAPIView