1👍
✅
This isn’t what SQL group by is — in SQL you would have to choose which of Bob or Sara would be returned for the Sales – 12/12 row, you couldn’t have both. I’d do this processing in Python, there’s no real SQL for what you want.
For instance, keep a dictionary of (department name, date) tuples and a list of names as values:
from collections import defaultdict
table = defaultdict(list)
for department, date, name in Person.objects.values_list(
'department__name', 'start_date', 'name'):
table[(department, date)].append(name)
0👍
The way you can do your group_by in django is using values
and aggregate
.
For example, you can achieve the result you want by making it like this:
Person.objects.all().values('department__name', 'start_date').annotate(Count('start_date'))
However I believe you can not get all the names in a single string, and AFAIK you also could not do it in a simple GROUP BY
on mysql, for example.
EDIT: just now I’ve understood that you want to group_by two values, so you would do something like:
Person.objects.all().values('department__name', 'start_date')\
.annotate(Count('start_date'))\
.annotate(Count('department__name'))\
.values_list('department__name','start_date')
- Updating/overwriting HTML data with jQuery?
- Latest entry of every month
- How to insert data into django app database using a web API
- Can't route reset email link to password reset view
- Formatting job returned from input with Jquery
Source:stackexchange.com