2016-08-17 36 views
1

我想根據query_params在視圖上使用不同的分頁類集。Django Rest Framework(DRF)如何根據query_params設置分頁類?

class BlockViewSet(viewsets.ModelViewSet): 
    pagination_class = defaultPaginationClass 

    def get_queryset(self): 
     queryset = Block.objects.all() 
     user = self.request.query_params.get('user', None) 
     if user is no None: 
      queryset = queryset.filter(user=user) 
     return queryset 

所以如果GET請求來/block/發,我想用defaultPagination類,而如果該請求是/block/?user=1發,我想用customPagination類。

回答

2

嘗試重新定義paginator屬性,如果有用戶查詢參數,指定您的自定義分頁類self._paginator

@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: 
      user = self.request.query_params.get('user', None) 
      if user is not None: 
       self._paginator = customPaginationClass() 
      else: 
       self._paginator = self.pagination_class() 
    return self._paginator 

最終

class BlockViewSet(viewsets.ModelViewSet): 
    pagination_class = defaultPaginationClass 

    @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: 
       user = self.request.query_params.get('user', None) 
       if user is not None: 
        self._paginator = customPaginationClass() 
       else: 
        self._paginator = self.pagination_class() 
     return self._paginator 

    def get_queryset(self): 
     queryset = Block.objects.all() 
     user = self.request.query_params.get('user', None) 
     if user is no None: 
      queryset = queryset.filter(user=user) 
     return queryset 
+0

謝謝。像魅力一樣工作 – seibeki

相關問題