Django ORM按多列分组 [英] Django orm group by multiple columns
问题描述
如何在Django中执行多列分组?
我只在by的一个列组上看到过示例。
下面是我要转换为Django ORM的查询。
How to perform a multiple column group by in Django?
I have only seen examples on one column group by.
Below is the query i am trying to convert to Django ORM.
SELECT order_id,city,locality,login_time,sum(morning_hours),sum(afternoon_hours),sum(evening_hours),sum(total_hours)
FROM orders
GROUPBY order_id,city,locality,login_time`
推荐答案
from django.db.models import Sum
Your_Model.objects.values('order_id', 'city', 'locality', 'login_time').order_by().annotate(sum('morning_hours'), sum('afternoon_hours'), sum('evening_hours'), sum('total_hours'))
我希望以上代码段对您有所帮助(在回答时,我不知道上午,下午等是表中的派生列还是现有字段,因为您未在问题中指定任何种类。因此,我做出了假设并回答了您的问题)。对于按多列分组,已经存在关于SO的问题。参见此链接。
I hope the above code snippet helps (While answering, I had no idea whether morning hours, afternoon hours, etc are derived columns or existing fields in the table, because you have specified nothing of the sort in your question. Hence, I made my assumption and have answered your question). For grouping by multiple columns, there already exists a question on SO. See this link.
这篇关于Django ORM按多列分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!