Django - how to select unique values in col
I have a little problem with Django which I can't manage to solve. Suppose that I have models like this:
class Game(models.Model):
# some attributes here
class Score(models.Model):
user = models.ForeignKey(User)
game = models.ForeignKey开发者_如何学Go(Game)
val = models.IntegerField()
#...
Now, I want to keep in DB all the scores from last games, but when it comes to show their values on page I want to choose only the best score for chosen player in each game. How do I do that? Or maybe I have to change Score model?
Depending on your version of Django, you could do this:
from django.db.models import Max
player = User.objects.filter(username='user')
best_score = Score.objects.filter(user=player).aggregate(Max('val'))
For this you can use the Django Max funciton
from django.db.models import Max
_user = User.objects.get(...)
_game = Game.objects.get(...)
score = Score.objects.filter(user=_user,game=_game)
max_score = score.aggregate(Max('val'))
Since you are trying to do this for the display, I'd probably make it into a template filter...
@register.filter
def highest_score(user, game):
scores = Score.objects.filter(game=game, user=user).order_by("val")
return scores[0]
You'd need some error checking in there, obviously. For instance, you'll want to make sure that the "scores" queryset actually has results in it.
But, then you can use it in a template like this:
<p>{{ user }}'s top score: {{ user|highest_score:game }}</p>
I've finally found the solution. It's quite different from what you've given to me, but thanks for you all, because it turned my on right way to find the answer. You answers returns only one, the very best score of all the games player won. Each game is different from others so I have to keep them all. My deal was about to give best score for each game and return all these values at once.
My solution do, what I've wanted it to do:
user_id = req.GET['user_id']
player = User.objects.get(id__exact=user_id)
scores = score.objects.filter(user=player).values('game').order_by('game').annotate(best=Max('score'))
精彩评论