[ACCEPTED]-A QuerySet by aggregate field value-database
Accepted answer
Oh, of course I forget about new aggregation 2 support in Django and its annotate
functionality.
So 1 query may look like this:
Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )
You can write your own sort in Python very 3 simply.
def getScore( anObject ):
return anObject.score()
objects= list(Contest.objects.get( pk = id ).image_set)
objects.sort( key=getScore )
This works nicely because we sorted 2 the list, which we're going to provide to 1 the template.
The db-level order_by
cannot sort queryset by model's 4 python method.
The solution is to introduce 3 score
field to Image
model and recalculate it on every 2 Vote
update. Some sort of denormalization. When 1 you will can to sort by it.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.