2012-05-23 3 views
3

태그의 총 합계와 점수로 정렬 할 수 있도록 객체 목록 (각각 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',) 
    ) 
+0

중복 가능성 http://stackoverflow.com/questions/3160798/django-order-by-sum-of -fields) – DrTyrsa

+0

@DrTyrsa 나는 똑같은 일을하려하지만, 실제 필드와는 대조적으로 그 필드 중 하나를 사용합니다. – borntyping

+0

나는 denolmazition에 가겠다 :'tags_count' 파일을 모델에 추가하고 시그널로 업데이트한다. 또는 [원시 쿼리] (https://docs.djangoproject.com/en/dev/topics/db/sql/)를 대신 사용할 수 있습니다. – DrTyrsa

답변

1

사용 추가

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

멋진 copypasting. – DrTyrsa

+0

그냥 돕기 위해;) @DrTyrsa – Efazati

+0

@Efazati 이것은 작동하지 않습니다 - 데이터베이스는 django와 같은 번역을하지 않으므로 던졌습니다 : '렌더링 중에 데이터베이스 오류가 발생했습니다 : 해당 열 없음 : tags__count' – borntyping

관련 문제