Django sum a field based on foreign key -


so here models:

class puzzles(models.model):     user = models.foreignkey(user)     puzzle = models.charfield(max_length=200)   class scores(models.model):    user = models.foreignkey(user)    puzzle = models.foreignkey(puzzles)    score = models.integerfield(default=0) 

so user have multiple scores. leaderboard page want output users top overall score(added of different scores). i'm lost on python code this.

any appreciated, thanks!

the easiest way annotation.

from django.db.models import sum  best = user.objects.annotate(total_score=sum('scores__score')).order_by('-total_score')[0:10] 

the documentation has example that's pretty on point.


Comments

Popular posts from this blog

vb.net - Alternative to the T-SQL AS keyword -

php - MySQLi binding parameters in a prepared statement doesn't work unless inserted after "WHERE" -

ios - CFRelease causing crash in iPad application -