【问题标题】:How to get max score of answers to a question by each user如何获得每个用户对问题的答案的最高分数
【发布时间】:2022-01-25 20:46:29
【问题描述】:

我有这两个模型:

class Question(models.Model):
    title = models.CharField(max_length=200)
    # other fields

class Answer(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)
    score = models.IntegerField()  

每个用户可以多次回答一个问题。

想象一下我有这些答案:

{
     "user": 1,
     "question": 1,
     "score": 50
},
{
     "user": 1,
     "question": 1,
     "score": 100
},
{
     "user": 2,
     "question": 1,
     "score": 100
},
{
     "user": 2,
     "question": 1,
     "score": 200
},
{
     "user": 2,
     "question": 2,
     "score": 100
},
{
     "user": 2,
     "question": 2,
     "score": 200
}  

我想要一个查询给我这个结果:

{
     "user": 1,
     "question": 1,
     "max_score": 100
},
{
     "user": 2,
     "question": 1,
     "max_score": 200
},
{
     "user": 2,
     "question": 2,
     "max_score": 200
}  

我想要每个用户对每个答案的所有最高分数。

【问题讨论】:

    标签: django django-models django-queryset


    【解决方案1】:

    试试这个:

    from django.db.models import Max
    
    Answer.objects.all().values("user", "question").annotate(score=Max("score"))
    

    【讨论】:

      【解决方案2】:

      我不确定如何使用 Django ORM 实现您的目标,但您可以使用 RawSQL 来实现

      Answer.objects.raw("""
      select a1.* from answer a1 LEFT JOIN answer a2
          ON (
              a1.user_id = a2.user_id and a1.score < a2.score
          )
      where a2.user_id isnull
      """)
      

      解释:你只从你的表中得到记录,每个用户从同一个表中没有更大的score

      【讨论】:

      • 谢谢,但我不能使用原始查询。
      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 2016-08-12
      • 1970-01-01
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      相关资源
      最近更新 更多