分页在 DRF APIView 中不起作用 [英] Pagination not working in DRF APIView

查看:30
本文介绍了分页在 DRF APIView 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 APIView 来获取和发布项目.
我想使用 Django Rest Framework 为我的 API 实现分页,但它不起作用.

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.

我想每页显示 10 个项目,但是当我执行 api/v1/items?page=1 时,我得到了所有项目,如果我只执行 api/v1/items 我得到一个空列表.

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.

这是我所做的:

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)

推荐答案

非通用视图和视图集 默认情况下没有分页,如 django rest 框架文档中所述:

Non generic views and viewsets do not have pagination by default as stated in the django rest framework documentation:

只有在您使用通用视图或视图集时才会自动执行分页.如果您使用的是常规 APIView,则需要自己调用分页 API 以确保返回分页响应.有关示例,请参阅 mixins.ListModelMixingenerics.GenericAPIView 类的源代码.

Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.

我编写了一个 关于启用分页的完整示例非通用视图以及如何实现这一点的代码:

I have composed a full example on enabling pagination on non generic views with code on how to achieve this:

class ItemsAPIView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
    serializer_class = MyNewUnifiedSerializerClass

    def get(self, request):
        user_items =  BaseItem.objects.filter(
                          owner=request.user
                      ).distinct()
        page = self.paginate_queryset(user_items)

        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(user_items, many=True)
        return Response(serializer.data)

    # Now add the pagination handlers taken from 
    #  django-rest-framework/rest_framework/generics.py

    @property
    def paginator(self):
        """
        The paginator instance associated with the view, or `None`.
        """
        if not hasattr(self, '_paginator'):
            if self.pagination_class is None:
                self._paginator = None
            else:
                self._paginator = self.pagination_class()
            return self._paginator

     def paginate_queryset(self, queryset):
         """
         Return a single page of results, 
         or `None` if pagination is disabled.
         """
         if self.paginator is None:
             return None
         return self.paginator.paginate_queryset(
                    queryset, 
                    self.request, 
                    view=self
                )

     def get_paginated_response(self, data):
         """
         Return a paginated style `Response` object 
         for the given output data.
         """
         assert self.paginator is not None
         return self.paginator.get_paginated_response(data)

有关更多详细信息,请查看示例提供链接.

For more details have a look at the example link provided.

这篇关于分页在 DRF APIView 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆