问题描述
我正在使用APIView获取和发布项目。我想在我的API中实现分页系统,但分页不起作用。我想显示每页10个项目,但是当我执行 api / v1 / items?page = 1
,我得到所有的项目,如果我只是做 api / v1 / items
我得到空列表。
I am using APIView for get and post items. I wanted to implement a pagination system in my API but the pagination 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 empty list.
在Django Rest Framework中使用APIView时,如何使用分页功能?
How can i use pagination feature when using APIView in Django Rest Framework?
这是我所做的django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
class Items APIView(APIView):
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)
推荐答案
扩展 GenericAPIView
而不是 APIView
并定义 pagination_class
在 GenericAPIView
extend GenericAPIView
instead of APIView
and define pagination_class
in GenericAPIView
这篇关于分页不能在DRF APIView中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!