2016-10-07 16 views
0

I持つ結果のセットを出力ビューセット:集計合計枠組み

{ 
    "count": 19355, 
    "next": null, 
    "previous": null, 
    "results": [ 
     { 
      "duration": 5, 
      ... 
     }, 
     { 
      "duration": 5, 
      ... 
     }, 
     ... 
    ] 
} 

私は右のそれ便利な小さなで、結果の期間の合計を集計したいと思います「カウント」の横の上の領域。私は注釈と和を使ってクエリーセットでこれを行う方法を知っていますが、ViewSetの出力にそれを取得する方法はありません。このデータ・セットの

所望の出力は次のようになります。

{ 
    "count": 19355, 
    "total_duration": 10, 
    "next": null, 
    "previous": null, 
    "results": [ 
     { 
      "duration": 5, 
      ... 
     }, 
     { 
      "duration": 5, 
      ... 
     }, 
     ... 
    ] 
} 

私は助けに感謝します!

+0

ビューセットの出力を見ると、ページネーションを使用していますか? 'total_duration'をページまたは全クエリーセットの期間の合計にしますか? –

+0

はい、私はそれを全体クエリーセットの合計としたいと思います。私は別のDBクエリを必要とする可能性があると、それは問題ありません。私はちょうど集計のためにまったく新しいエンドポイントを作成しないでください。 – Ben174

答えて

4

専用のPaginationクラスを使用して実装することをお勧めします。

class PaginationWithAggregates(pagination.LimitOffsetPagination): 
    def paginate_queryset(self, queryset, request, view=None): 
     self.total_duration = queryset.aggregate(total_duration=Sum('duration'))['total_duration'] 
     return super(PaginationWithAggregates, self).paginate_queryset(queryset, request, view) 

    def get_paginated_response(self, data): 
     paginated_response = super(PaginationWithAggregates, self).get_paginated_response(data) 
     paginated_response.data['total_duration'] = self.total_duration 
     return paginated_response 

このページネーション・クラスをGenericViewで宣言するのを忘れないでください。

+0

独創的!これをページネーションクラスに入れることは決して考えていませんでした。チャームのように働いています(レスポンスヘッダーではなく、total_durationをデータペイロードに移動するためにソリューションを編集する必要がありました)ありがとうございました! – Ben174