我想注释一个对象列表(每个对象都有一组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',)
)