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

Foreign key annotation returns foreign keys. How can I get objects from a request? In the following example, the_user is a foreign key in the Voting model:

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

He will return

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

But I need custom objects themselves. Non identifiers

+6
source share
3 answers

values() does just that - returns values, uses a regular query

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

Then each object in this request will have a vote_count attribute.

0
source

You should always ask the model for the objects you want to return to the given set of queries, so in your case:

 qs = User.objects.annotate(vote_count=Count('vote')).order_by('-vote_count') 
0
source

The reason you get the foreign key, not user objects, is because you use values ​​(), the values ​​return a dict object, not a model object. Use select_related instead of values ​​and this will solve your problem.

-1
source

Source: https://habr.com/ru/post/886101/


All Articles