Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to get objects instead of just foreign keys in annotate?

Tags:

django

Annotate on a foreign key returns foreign keys. How can I get the objects themselves from the query? In the following example 'the_user' is a foreign key in the "Vote" model:

Vote.objects.values('the_user').annotate(vote_count=Count('the_user')).order_by('-vote_count')

It would return

[{'the_user': 4, 'vote_count': 12} , {'the_user': 6, 'vote_count': 2}]

But I need the user objects themselves.. Not the ids

like image 738
GabiMe Avatar asked Apr 17 '11 21:04

GabiMe


1 Answers

values() does exactly that - returns values, use usual queryset

Vote.objects.annotate(vote_count=Count('the_user')).order_by('-vote_count')

Then each object in that queryset will have vote_count attribute.

like image 184
Dmitry Shevchenko Avatar answered Sep 24 '22 19:09

Dmitry Shevchenko