我想加注一个对象列表( 每个对象都有一套 tags
和一个整数值 points
), 以便按照标记加点的总计数进行分类。
然而,我无法用两栏之和来说明物体。
这些是我正在使用的模型,而lederboard ()
函数是我难以工作的模型。
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 ,)
)