从django orm中特定用户的最高分数中查找总分

Finding total score from specific user's maximum score in django orm

我有一个获取两个参数的函数(contest_id,user_id),我怎么能在给定用户的给定比赛中获得每个问题的最高分,然后总结所有这些最高分? 每个问题可以有零个或多个提交的分数。

例如:(problem_id,submitted_score) --> (1, 80), (1, 100), (2, 150), (2, 200), (3 , 220), (3, 300)

此示例的预期结果应为 600、100 + 200 + 300。

型号:

class Contest(models.Model):
    name = models.CharField(max_length=50)
    holder = models.ForeignKey(User, on_delete=models.CASCADE)
    start_time = models.DateTimeField()
    finish_time = models.DateTimeField()
    is_monetary = models.BooleanField(default=False)
    price = models.PositiveIntegerField(default=0)
    problems = models.ManyToManyField(Problem)
    authors = models.ManyToManyField(User, related_name='authors')
    participants = models.ManyToManyField(User, related_name='participants')

class Problem(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=1000)
    writer = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    score = models.PositiveIntegerField(default=100)

class Submission(models.Model):
    submitted_time = models.DateTimeField()
    participant = models.ForeignKey(User, related_name="submissions", on_delete=models.DO_NOTHING)
    problem = models.ForeignKey(Problem, related_name="submissions", on_delete=models.CASCADE)
    code = models.URLField(max_length=200)
    score = models.PositiveIntegerField(default=0)

你可以用相关 Submission 中最大的 score 注释 Problem,然后将它们加起来,所以:

from django.db.models import Max, Sum

Problem.objects.filter(
    contest__id=contest_id,
    submissions__participant_id=user_id
).annotate(
    <strong>max_score=Max('submissions__score')</strong>
).aggregate(
    <strong>total=Sum('max_score')</strong>
)

这将生成如下所示的查询:

SELECT <strong>SUM(max_score)</strong>
FROM (
    SELECT <strong>MAX(submission.score)</strong> AS max_score
    FROM problem
    INNER JOIN contest_problems ON problem.id = contest_problems.problem_id
    INNER JOIN submission ON problem.id = submission.problem_id
    WHERE contest_problems.contest_id = <em>contest_id</em>
      AND submission.participant_id = <em>user_id</em>
    <strong>GROUP BY problem.id</strong>
) subquery

如果对于给定的上下文,任何 Problem 都没有相关的 Submission,它将 return NULL/None 而不是 0.