2016-03-06 120 views
10

我有一個非常簡單的APIView,但我不知道如何在這裏設置分頁。 在這種情況下,我選擇Event與給定pk,然後我得到所有NewsItems分配給此EventDjango Rest框架 - APIView分頁

pagination_class = LimitOffsetPagination工作正常,當我在ListCreateAPIView開始定義查詢集,例如。 queryset = Event.objects.all()但與定製get

class EventNewsItems(APIView): 
    pagination_class = LimitOffsetPagination 

    def get(self, request, pk, format=None): 

     #user = request.user 
     event = Event.objects.get(pk=pk) 
     news = event.get_news_items().all() 

     serializer = NewsItemSerializer(news, many=True, context={'request':request}) 
     response = Response(serializer.data, status=status.HTTP_200_OK) 
     return response 

解決:

def get(self, request, pk, format=None): 

    #user = request.user 
    event = Event.objects.get(pk=pk) 
    news = event.get_news_items().all() 
    paginator = LimitOffsetPagination() 
    result_page = paginator.paginate_queryset(news, request) 
    serializer = NewsItemSerializer(result_page, many=True, context={'request':request}) 
    response = Response(serializer.data, status=status.HTTP_200_OK) 
    return response 
+2

回顧這次討論中,看起來像這個傢伙的解決您的問題https://github.com/tomchristie/django-rest-framework/issues/ 3030 – inlanger

+0

嘿,@ user3128673我想知道你是否發現我的答案有幫助。 –

回答

4

我已經創建了關於這個問題的一個Q&A style example
作爲一種總結:

通過利用Django的休息框架源代碼,他們如何處理分頁,我們創建的視圖類裏面相同的方法和我們使用它們,在解決方案中使用默認的方法是相同的:

從上面提到的文檔摘自:

from rest_framework.settings import api_settings 
from rest_framework.views import APIView 

class MyView(APIView): 
    queryset = OurModel.objects.all() 
    serializer_class = OurModelSerializer 
    pagination_class = api_settings.DEFAULT_PAGINATION_CLASS # cool trick right? :) 

    # We need to override get method to achieve pagination 
    def get(self, request): 
     ... 
     page = self.paginate_queryset(self.queryset) 
     if page is not None: 
      serializer = self.serializer_class(page, many=True) 
      return self.get_paginated_response(serializer.data) 

     ... Do other stuff needed (out of scope of pagination) 

    # 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)