django aggregation: sum then average

前端 未结 2 1128
北海茫月
北海茫月 2021-02-07 07:11

Using django\'s ORM annotate() and/or aggregate(): I want to sum up based on one category field and then average over the category values per date. I tried to do it using two an

2条回答
  •  孤街浪徒
    2021-02-07 07:56

    Aggregate annotation by group from many aggregate annotations by group is generally a complicated question, but Avg from Sum is a special much easier case.

    Expression Avg('sum_for_field') can be evaluated as Sum('sum_for_field') / Count('category', distinct=True) that can be evaluated by Aggregate() expressions. The Sum('sum_for_field') equals Sum('amount').

    Solution: (Expected names: The model is Data that has fields date, category, amount.)

    qs = Data.objects.values('date').annotate(
        avg_final=Sum('amount') / Count('category', distinct=True)
    )
    

    (I'm convinced that very similar questions would be without any solution by current Django 1.11, even with Subquery class, without using a strange extra() method and without raw SQL)

提交回复
热议问题