2016-01-16 128 views
0

我試圖讓我的API每頁最多返回10個。這有助於我無限加載。該API網址將我試圖看起來像這樣:Django Rest框架分頁

www.mysite.com/api/test/?user=5&page=1 

但是,這是行不通的。

我跟着官方docs here without成功。

我只修改了兩個文件,settings.py & rest_views.py。

settings.py-

REST_FRAMEWORK = { 
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' 
} 

rest_views.py-

from django.core.paginator import Paginator 

... 

wardrobematch = { 
    'user': lambda x: ('user__pk', x) 
} 

class WardrobeListView(APIView): 

    renderer_classes = (JSONRenderer,) 
    paginate_by = 10 
    paginate_by_param = 'page_size' 
    max_paginate_by = 100 

    def get(self, request, *args, **kwargs): 

     filters = {} 
     for key, value in request.GET.items(): 
      key = key.lower() 
      if key in wardrobematch: 
       lookup, val = wardrobematch[key](value.lower()) 
       filters[lookup] = val 

     qset = (
      Analytic.objects 
      .filter(like=True,**filters) 
      .order_by('-updated',) 
      # .distinct('product_id',) 
      .values('product_id', 'product__name', 'product__brand', 'product__store__store_name', 'product__variation__image__image', 'product__variation__price__price',) 
     ) 

     return Response(qset) 

回答

0

我得到了你的第一個例子working-對我來說是更清晰和更基本的。我所做的只是添加「.object_list」來停止「不是JSON序列化」錯誤。

這是你的答案跟我的小的調整:

class WardrobeListView(APIView): 

    renderer_classes = (JSONRenderer,) 

    def get(self, request, *args, **kwargs): 

     filters = {} 
     for key, value in request.GET.items(): 
      key = key.lower() 
      if key in wardrobematch: 
       lookup, val = wardrobematch[key](value.lower()) 
       filters[lookup] = val 

     qset = (
      Analytic.objects 
      .filter(like=True,**filters) 
      .order_by('-updated',) 
      # .distinct('product_id',) 
      .values('product_id', 'product__name', 'product__brand', 'product__store__store_name', 'product__variation__image__image', 'product__variation__price__price',) 
    ) 
     paginator = Paginator(qset, 2) # Show 25 items per page 

     page = request.GET.get('page') 
     try: 
      qset = paginator.page(page) 
     except PageNotAnInteger: 
      # If page is not an integer, deliver first page. 
      qset = paginator.page(1) 
     except EmptyPage: 
      # If page is out of range (e.g. 9999), deliver last page of results. 
      qset = paginator.page(paginator.num_pages) 

     return Response(qset.object_list) 
1

當使用普通ApiView,你應該自己調用API分頁,它不會自動執行分頁。

我已經創建了一個分頁和一個序列化器mixim。我不確定這是最好的方法,但它對我有用。

class SerializerMixim(object): 

    def serialize_object(self,obj): 
     """Serilize only needed fields""" 
     return NotImplementedError 


class PaginationMixim(object): 

    _serializer = None 

    def paginate(self,queryset,num=10): 
     page = self.request.GET.get('page') 
     paginator = Paginator(queryset, num) 
     try: 
      queryset = paginator.page(page) 
     except PageNotAnInteger: 
      queryset = paginator.page(1) 
     except EmptyPage: 
      queryset = paginator.page(paginator.num_pages) 
     count = paginator.count 
     previous = None if not queryset.has_previous() else queryset.previous_page_number() 
     next = None if not queryset.has_next() else queryset.next_page_number() 
     if self._serializer: 
      objects = self._serializer(queryset.object_list,many=True).data 
     else: 
      objects = [self.serialize_object(i) for i in queryset.object_list] 

     data = {'count':count,'previous':previous, 
       'next':next,'object_list':objects} 
     return Response(data) 

    def serialize_object(self,obj): 
     return {'id':obj.pk} 


class WardrobeListView(APIView,PaginationMixim,SerializerMixim): 

    renderer_classes = (JSONRenderer,) 
    #_serializer = AnalyticSerializer 
    def get(self, request, *args, **kwargs): 

     filters = {} 
     for key, value in request.GET.items(): 
      key = key.lower() 
      if key in wardrobematch: 
       lookup, val = wardrobematch[key](value.lower()) 
       filters[lookup] = val 

     qset = (
      Analytic.objects 
      .filter(like=True,**filters) 
      .order_by('-updated',) 
      # .distinct('product_id',) 


     return self.paginate(qset) 

    def serialize_object(self,obj): 
     return obj.serilized 

,那麼你需要創建一個分析模型就像一個屬性格式,

class Analytic(models.Model): 
    ..... 

    @property 
    def serilized(self): 

     summary = { 
      'id':self.product.id, 
      'image':self.product.name, 
      ....... 
     } 
     return summary 

這也將與Django的休息串行工作

+0

啊我見式這個答案讓我輸入錯誤(<146 1>不是JSON序列化)。我以前沒有過。你能建議嗎? – Ycon

+0

這是我的錯誤回溯http://dpaste.com/2EA0KEJ – Ycon

+0

對不起,延遲。我更新了代碼。請嘗試.. – Anoop