Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing "group by" in django but still retaining complete object

I want to do a GROUP BY in Django. I saw answers on Stack Overflow that recommend:

Member.objects.values('designation').annotate(dcount=Count('designation'))

This works, but the problem is you're getting a ValuesQuerySet instead of a QuerySet, so the queryset isn't giving me full objects but only specific fields. I want to get complete objects.

Of course, since we're grouping we need to choose which object to take out of each group; I want a way to specify the object (e.g. take the one with the biggest value in a certain field, etc.)

Does anyone know how I can do that?

like image 627
Ram Rachum Avatar asked Jun 04 '14 12:06

Ram Rachum


1 Answers

If you're willing to make two queries, you could do the following:

dcounts = Member.objects.values('id', 'designation').annotate(dcount=Count('designation')).order_by('-dcount')
member = Member.objects.get(id=dcounts.first()['id'])

If you wanted the top five objects by dcount, you could do the following:

ids = [dcount['id'] for dcount in dcounts[:5]]
members = Member.objects.filter(id__in=ids)
like image 73
kronosapiens Avatar answered Oct 05 '22 23:10

kronosapiens