【问题标题】:Aggregate totals of a ViewSet results in Django Rest Framework在 Django Rest Framework 中汇总 ViewSet 结果的总数
【发布时间】:2016-10-07 00:12:55
【问题描述】:

我有一个输出一组结果的 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,
            ...
        },
        ...
    ]
}

感谢您的帮助!

【问题讨论】:

  • 查看视图集的输出,您正在使用分页,不是吗?您希望 total_duration 成为页面持续时间的总和还是整个查询集的总和?
  • 是的,我希望它是整个查询集的总数。我想这可能需要另一个数据库查询,这很好。我宁愿不为聚合创建一个全新的端点。

标签: django django-rest-framework


【解决方案1】:

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

【讨论】:

  • 巧妙!从来没想过把它放在分页课上。像魅力一样工作(必须对您的解决方案进行一些编辑以将 total_duration 移动到数据有效负载,而不是响应标头。)谢谢!
  • 太棒了!这完全有效,节省了我几个小时。谢谢@迈克尔。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-01
  • 2014-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多