ViewSet的总计结果导致Django Rest Framework

时间:2016-10-07 00:12:56

标签: django django-rest-framework

我有一个ViewSet,它输出一组结果:

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

我想汇总结果持续时间的总和,就在“计数”旁边那个方便的小顶部区域。我知道如何使用annotate和sum在查询集中执行此操作,但我没有看到将其放入ViewSet输出的方法。

此数据集的所需输出为:

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

我很感激帮助!

1 个答案:

答案 0 :(得分:5)

我建议使用专用的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上声明这个分页类。