Django: How can I annotate on the Sum of values in a ForeignKey relationship? -


i have 2 models, item , vote:

class item(models.model):     name=charfield(max_length=75)  class vote(models.model):     item = foreignkey(item)     value = integerfield() 

i want provide queryset list of items in order of sum of value of votes. i'm trying:

items = item.objects.annotate(sum('votes__value')).order_by('votes__value') 

but in situation have 2 votes - 1 value = 0 , 1 value = 1 - i'm getting queryset of 2 item instances, item1 == item2!

how construct queryset? thanks!

try this;

items = item.objects.values('item').annotate(votes_value=sum('votes')).order_by('votes') 

or

items = item.objects.values('item').annotate(votes_value=sum('votes')) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -