Django querysets select average and best result
I have a model like this:
class Quiz(models.Model):
user = models.ForeignKey(User, unique=True)
school_class = models.CharField(max_length=3, choices=klasa_choices)
points = models.DecimalField(max_digits=5, decimal_places=2,default=0)
date = models.DateTimeField(null=True,blank=True)
active = models.BooleanField(default=False)
Basically I'd like to get the average score (points) and the best result with the corresponding user for each school_class . Can this be done easily? (i.e without additional computing?)
So far I've come to:
Quiz.objects.values('school开发者_如何学Python_class').annotate(avg=Avg('points'),max=Max('points')).order_by('-avg')
but how do I also get the user with the best score?
You need a second query. You can use the results of the first one to save on ordering your tables:
quizzes = Quiz.objects.values('school_class').annotate(avg=Avg('points'),max=Max('points')).order_by('-avg')
Quiz.objects.values('user','school_class').filter(points=quizzes.max)
If you only want one, add .latest('date'), .latest('-date'), or [0] to get just one.
精彩评论