1

所以这是我的模型:

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)

所以一个用户会有多个分数。对于排行榜页面,我想输出总分最高的用户(从所有不同的分数中添加)。我真的不知道python代码会做什么。

任何帮助表示赞赏,谢谢!

4

3 回答 3

8

最简单的方法是使用注释。

from django.db.models import Sum

best = User.objects.annotate(total_score=Sum('scores__score')).order_by('-total_score')[0:10]

该文档有一个非常恰当的示例

于 2013-08-13T06:04:04.340 回答
0

I think the best way to do this would be to make user profile model with a totalscore field. Then you can use a signal tied to the saving of score models to update the totalscore field. See below for help on using signals.

django how do i send a post_save signal when updating a user? https://docs.djangoproject.com/en/dev/ref/signals/

Then, you can simply do UserProfile.objects.all().order_by('totalscore')

Edit: Here is some information on user profiles. They should have a one-to-one with a User, and can then contain any custom fields that you like. Django user profile

于 2013-08-13T01:52:50.920 回答
0

这是所有谜题的排行榜页面还是只有一个?如果您可以尝试以下方法:

Score.objects.all().order_by('score')[:10] # limit 10
于 2013-08-13T01:24:44.903 回答