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

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -