[ACCEPTED]-A QuerySet by aggregate field value-database

Accepted answer
Score: 47

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' )
Score: 9

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.

Score: 2

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.

More Related questions