我需要找到一个类别中具有最大测试分数的用户id的最大分数。
我的型号:
class QuizCat(models.Model):
cid = models.IntegerField(unique=True)
c_name = models.CharField(max_length=200)
class Quiz(models.Model):
Qid = models.IntegerField()
cat_id = models.ForeignKey(QuizCat, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
class UserDetails(models.Model):
user_id = models.IntegerField()
Qid = models.ForeignKey(Quiz, on_delete=models.CASCADE)
score = models.IntegerField()
我试过了:
category_id = request.GET.get('category_id')
result = UserDetails.objects.all().values('user_id').annotate(score=Sum('score')).filter(Qid__cat_id=category_id)
但上述措施并未奏效。
使用Max
:而不是求和
result = UserDetails.objects.filter(Qid__cat_id=category_id).values('user_id').annotate(score=Max('score'))