[Fixed]-Django ORM group by

1👍

Change your values queryset to fetch the tmp field as well

queryset = A.objects.all().values('id', 'tmp')

then construct the dictionary you need using a defaultdict

from collections import defaultdict
d = defaultdict(list)
for q in queryset:
    d[q['tmp']].append(q['id'])

The result d will be a dictionary with tmp as the keys. This is slightly different than in your question (you have a list of dictionaries, each with one key). You can adjust the code if you need a different data structure.

Leave a comment