2017-10-04 10 views
1

用のカスタムPAGE_SIZEは、私がlist_routeを持っている:Djangoの残りのフレームワーク、list_routeアクション

@list_route(methods=['get']) 
    def bought(self, request): 
     bought_photos = Photo.objects.filter(is_bought=True) 

     page = self.paginate_queryset(bought_photos) 
     if page is not None: 
      serializer = self.get_serializer(page, many=True) 
      return self.get_paginated_response(serializer.data) 
     serializer = self.get_serializer(bought_photos, many=True) 
     return Response(serializer.data) 

私はlist_routeのためではなく、そのModelViewSetにカスタムPAGE_SIZEを設定できますか?

SOLUTION

1)list_routeコード編集)

from rest_framework.pagination import PageNumberPagination 

class CustomPagination(PageNumberPagination): 
    page_size = 10000 
    page_size_query_param = 'page_size' 

2 CustomPaginationクラスを作成します。私は、次のコードは十分なはずだと思う

@list_route(methods=['get']) 
    def bought(self, request): 
     bought_photos = Photo.objects.filter(is_bought=True) 
     paginator = CustomPagination() 

     page = paginator.paginate_queryset(bought_photos, request) 
     if page is not None: 
      serializer = self.get_serializer(page, many=True) 
      return paginator.get_paginated_response(serializer.data) 
     serializer = self.get_serializer(bought_photos, many=True) 
     return Response(serializer.data) 

答えて

1

を:

@list_route(methods=['get'], pagination_class=CustomPagination) 
def bought(self, request): 
    bought_photos = Photo.objects.filter(is_bought=True) 

    page = self.paginate_queryset(bought_photos) 
    if page is not None: 
     serializer = self.get_serializer(page, many=True) 
     return self.get_paginated_response(serializer.data) 
    serializer = self.get_serializer(bought_photos, many=True) 
    return Response(serializer.data) 
+0

ニース!ありがとう!それはどこで読むことができますか? – user1518217

+0

これは、[documentation](http://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing)の中で本当に簡単な言及です。「デコレータは、たとえば、ルーティングされたビューに対してのみ設定される引数。たとえば、... " – Linovia

+0

フレームワークのいくつかの非常に高度なトピックと何らかの形で隠された機能について偉大な回答を読むことに驚いています。この答えが誉められていないことは残念です。たった一つの注釈: 'page'は' list'型でなければならないので、 'None'にすることはできないので、常にif節を入力します。リストが空の場合、if節を入力すべきではないので、条件は 'if page:'であるべきである。それとも、私は何か間違っているのでしょうか? – cezar

関連する問題