2017-02-20 58 views
1

有一個模型,它看起來像這樣 player_info,遊戲,比分,CREATION_DATEDjango的最大和GROUPBY我共同

我想每個玩家的特定遊戲的最高分取的記錄。

任何幫助表示讚賞。

編輯:

class Game(models.Model): 
    name = models.CharField(max_length=50) 
    description = models.TextField(max_length=1000) 
    logo = models.URLField() 
    resource_info = models.URLField() 
    cost = models.DecimalField(default=0.0, decimal_places=2, max_digits=10) 
    modified_date = models.DateTimeField(auto_now_add=True) 
    developer_info = models.ForeignKey(User, related_name='uploaded_games', on_delete=models.CASCADE) 

class Score(models.Model): 
    game_info = models.ForeignKey(Game, related_name='game_info',on_delete=models.CASCADE) 
    player_info = models.ForeignKey(User, related_name='player_info', on_delete=models.CASCADE) 
    last_played = models.DateTimeField(auto_now=True) 
    score = models.BigIntegerField(default=0) 
+0

你能否提供一些代碼?像所有相關領域的相關模型一樣?並且還嘗試了什麼查詢/查詢。 – JoseKilo

+0

這是我的模型看起來怎麼樣 類分數(models.Model): game_info = models.ForeignKey(遊戲,related_name = 'game_info',on_delete = models.CASCADE) player_info = models.ForeignKey(用戶,related_name = 'player_info',on_delete = models.CASCADE) last_played = models.DateTimeField(auto_now =真) 得分= models.BigIntegerField(缺省值= 0) 類遊戲(models.Model): 名稱= models.CharField(MAX_LENGTH = 50) description = models.TextField(max_length = 1000) resource_info = models.URLField()developer_info = models.ForeignKey(User,related_name ='uploaded_games',on_delete = models.CASCADE) – Coder

回答

0

如果我理解正確:

  • 你想通過GamefilterScore秒。
  • 然後你要GROUP BYUser並獲得MAX得分

GROUP BY部分是有點棘手,但可以使用values + annotate實現它。

嘗試這樣:

from django.db.models import Max 

Score.objects.filter(game_info=...) 
    .values('player_info').annotate(max=Max('score')) 

更多信息的例子:https://docs.djangoproject.com/en/1.10/topics/db/aggregation/