如何通过总共两个字段对django查询集进行排序?

时间:2012-05-23 10:33:37

标签: django django-models django-orm

我想要注释一个对象列表(每个对象都有一组tags和一个整数值points),这样它们就可以按标签总数加点数进行排序。

但是,我找不到任何方法用两列的总和来注释对象。知道如何做到这一点吗?

这些是我正在使用的模型,leaderboard()函数是我在工作上遇到困难的函数。

class Game (models.Model):
    users = models.ManyToManyField(User, through='Player', related_name='games')

    def leaderboard (self):
        """ Return a list of players ranked by score, where score is the total of the count of the players tags and their points. """
        leaderboard = self.player_set.annotate(
            tagcount=models.Count('tags')
        ).extra(
            select={'score': 'tagcount + points'},
            order_by=('score',)
        )
        return leaderboard

class Player (models.Model):
    game = models.ForeignKey(Game)
    user = models.ForeignKey(User)
    points = models.SmallIntegerField(default=0, help_text="Points that have been awarded to the player")

class Tag (models.Model):
    game = models.ForeignKey(Game, related_name='tags')
    player = ForeignKey(Player, related_name='tags')

编辑2 使用额外

的解决方案

好的,所以我得到了额外的工作,通过手动计算标签的数量并将其添加到点。

def leaderboard (self):
    """ Return a list of players ranked by score, where score is the total of the count of the players tags and their points. """
    return self.players.extra(
        select={'score': '(select count(*) from kaos_tag where kaos_tag.tagger_id=kaos_player.id) + points'},
        order_by=('-score',)
    )

1 个答案:

答案 0 :(得分:1)

使用额外的

players.objects.extra(
    select={'fieldsum':'tags__count + points'},
    order_by=('fieldsum',)
)