Aggregation of an annotation in GROUP BY in Django

后端 未结 4 486
太阳男子
太阳男子 2021-01-30 02:20

UPDATE

Thanks to the posted answer, I found a much simpler way to formulate the problem. The original question can be seen in the revision history.

4条回答
  •  不要未来只要你来
    2021-01-30 02:55

    This is expected from the way group_by works in Django. All annotated fields are added in GROUP BY clause. However, I am unable to comment on why it was written this way.

    You can get your query to work like this:

    Title.objects
      .values('publisher')
      .annotate(total_dbl_price=Sum(2*F('price'))
    

    which produces following SQL:

    SELECT publisher, SUM((2 * price)) AS total_dbl_price
    FROM title
    GROUP BY publisher
    

    which just happens to work in your case.

    I understand this might not be the complete solution you were looking for, but some even complex annotations can also be accommodated in this solution by using CombinedExpressions(I hope!).

提交回复
热议问题