2016-04-27 64 views
0

我有進行分頁記錄(每頁10條)如下一種觀點:如何在Django REST中處理當前頁面的記錄?

class Foo(models.Model): 
    bar = models.BooleanField(db_index=True) 
    user = models.ForeignKey(User, db_index=True, editable=False) 
    baz = models.CharField(max_length=120) 
    created = models.DateTimeField(db_index=True, auto_now_add=True) 
    updated = models.DateTimeField(auto_now=True) 

class UserSerializer(ModelSerializer): 
    class Meta: 
     model = User 
     fields = ('id', 'username') 

class FooSerializer(ModelSerializer): 
    user = UserSerializer() 
    class Meta: 
     model = Foo 

class FooPagination(PageNumberPagination): 
    page_size = 10 

class FooView(ListAPIView): 
    serializer_class = FooSerializer 
    pagination_class = FooPagination 
    def get_queryset(self): 
     user = self.request.user 
     '''   
     Do something here (or when page is requested) with each record on 
     the current page. 
     ''' 
     return Foo.objects.filter(bar=true, user=user).order_by('created') 

我如何處理美孚僅記錄在當前頁面上?

回答

1

也許有更好的解決辦法,但我不得不推出自己的View類做後期處理過濾和分頁的查詢集之後,但在它被序列化:

class DecoratedListModelMixin(object): 
    """ 
    Apply a decorator to the list view before serializing 
    """ 
    def list(self, request, *args, **kwargs): 
     has_decorator = (hasattr(self, 'decorator') and self.decorator is not None) 

     queryset = self.filter_queryset(self.get_queryset()) 
     page = self.paginate_queryset(queryset) 

     if page is not None: 

      if has_decorator: 
       serializer = self.get_serializer(self.decorator(page, request), many=True) 
      else: 
       serializer = self.get_serializer(page, many=True) 
      return self.get_paginated_response(serializer.data) 

     if has_decorator: 
      serializer = self.get_serializer(self.decorator(queryset, request), many=True) 
     else: 
      serializer = self.get_serializer(queryset, many=True) 
     return Response(serializer.data) 

class DecoratedListAPIView(DecoratedListModelMixin, generics.GenericAPIView): 
    def get(self, request, *args, **kwargs): 
     return self.list(request, *args, **kwargs) 

用法:

class FooView(DecoratedListAPIView): 
    serializer_class = FooSerializer 
    pagination_class = FooPagination 
    decorator = foo_decorator 
    def get_queryset(self): 
     user = self.request.user 
     return Foo.objects.filter(bar=true, user=user).order_by('created') 

# queryset contains current page only 
def foo_decorator(view, queryset, request): 
    for foo in queryset: 
     #... 
    return queryset 
+0

我用:「def foo_decorator(obj,queryset,request)」和ListAPIView而不是GenericAPIView。 – tyebillion

+0

裝飾工作正常,但我沒有收到JSON結果字段中的任何數據。 – tyebillion

+0

...即使計數不爲零。 – tyebillion

相關問題