태그의 총 합계와 점수로 정렬 할 수 있도록 객체 목록 (각각 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',)
)
중복 가능성 http://stackoverflow.com/questions/3160798/django-order-by-sum-of -fields) – DrTyrsa
@DrTyrsa 나는 똑같은 일을하려하지만, 실제 필드와는 대조적으로 그 필드 중 하나를 사용합니다. – borntyping
나는 denolmazition에 가겠다 :'tags_count' 파일을 모델에 추가하고 시그널로 업데이트한다. 또는 [원시 쿼리] (https://docs.djangoproject.com/en/dev/topics/db/sql/)를 대신 사용할 수 있습니다. – DrTyrsa