开发者

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

Anno开发者_如何学JAVAtate 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


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.


You should always query on the model which objects you want to get back in the resulted query set, so in your case:

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


The reason you are getting the foreign key and not the user objects is because of your use of values(), values returns a dict and not the model object. Use a select_related instead of values and that will resolve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜