2017-10-17 100 views
1

我想添加一個自定義paginator到我的Django API,但我不知道如何限制get_sdc_data()中paginator_class中每頁的項目數。Django的每頁設置項目Tastypie Paginator

class CustomApplicationSDCResource(AppMapBaseResource): 
    class Meta(AppMapBaseResource.Meta): 
     #import pdb;pdb.set_trace() 
     queryset = Applications.objects.all() 
     resource_name = 'applications' 
     allowed_methods = {'get'} 
     allowed_models = ['Applications'] 
     paginator_class = Paginator 


    def prepend_urls(self): 
     return [url(r"^(?P<resource_name>%s)/get_sdc_data%s$" % \ 
      (self._meta.resource_name, trailing_slash()), self.wrap_view('get_sdc_data'), name="api_get_sdc_data"), 
     ] 


    def get_sdc_data(self, request, **kwargs): 
     try: 
      sdc_list = [] 
      limit=request.GET.get('limit') 
      next_item = request.GET.get('next') 
      if request.GET.has_key('uaid'): 
       search_uaid=request.GET.get('uaid') 
       sdc_obj = Applications.objects.filter(Q(uaid__contains=search_uaid, status='Active')) 
      else: 
       sdc_obj = Applications.objects.all() 
      exc=['vendor_name', 'ldrps_app_rto','alias_name'] 
      import pdb;pdb.set_trace() 
      sdc_list = [model_to_dict(obj, exclude=exc) for obj in sdc_obj] 
      paginator = self._meta.paginator_class(request.GET, sdc_list, resource_uri=self.get_resource_uri(), \ 
      limit=limit, max_limit=self._meta.max_limit, collection_name=self._meta.collection_name) 
      paginated = paginator.page() 
      paginated['Applications'] = paginated.pop('objects') 
      return self.create_response(request, {"result" : paginated}) 
     except Exception as e: 
      print 'Problem in getting SDC Applications data. Error is ' + str(e) 

回答

0

一種方法是切片過濾器queryset。

# Pseudocode 
offset = request.get('offset', 0) 
limit = request.get('limit', 10) 
obj_queryset = Instance.objects.filter(foo=bar)[offset:limit] 

所以從客戶端只要告訴所需的分頁集。 希望這有助於。