Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django orm group by multiple columns

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`
like image 307
Shiva Rama Krishna Avatar asked May 27 '16 12:05

Shiva Rama Krishna


1 Answers

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'))

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.

like image 145
Shubhanshu Avatar answered Oct 03 '22 10:10

Shubhanshu