FK上的django计数,带总和和过滤器

FK上的django计数,带总和和过滤器,django,django-orm,Django,Django Orm,我必须找到两个字段之和高于给定字段的参与者数量。以下型号: class Examination(models.Model): total_score = models.FloatField(_('Total score'), blank=False, null=False, default=60) class ExamParticipation(models.Model): examination = models.ForeignKey(Examination, blank=F

我必须找到两个字段之和高于给定字段的参与者数量。以下型号:

class Examination(models.Model):
    total_score = models.FloatField(_('Total score'), blank=False, null=False, default=60)

class ExamParticipation(models.Model):
    examination = models.ForeignKey(Examination, blank=False, null=False, on_delete=models.CASCADE, related_name='examination_participations')
    total_score = models.DecimalField(_('examination score'), max_digits=3, decimal_places=1, default=0)
    additional_score = models.DecimalField(_('additional score'), max_digits=3, decimal_places=1, default=0)
因此,对于给定的考试,我必须计算有多少参与者,其中总分数和附加分数之和等于总分数/2。这在查询集上是可行的还是我必须循环结果

我尝试了以下查询:

    def count_sufficient_participations(self):
        qs = self.values('examination_participations').order_by('examination_participations').annotate(
        ts=Sum(F('examination_participations__total_score') + F('examination_participations__additional_score'))
    ).annotate(cnt_suff=Count('examination_participations')).filter(ts__gte=30)

但这似乎不起作用,我不知道如何用考试的现场总分代替30分。我想为我的模板提供类似examice.cnt_suff的内容。任何帮助都将不胜感激。

Sum
是一个
aggregate
函数,它意味着保留与查询匹配的列的所有值

但您希望对当前行的2列求和

所以使用

ts = F('examination_participations__total_score') + F('examination_participations__additional_score')
而不是

ts = Sum(F('examination_participations__total_score') + F('examination_participations__additional_score'))

我找到了以下解决方案:

def count_sufficient_participations(self):
    qs = self.annotate(
        cnt_suff=Count('examination_participations', filter=Q(total_score__lte=(F('examination_participations__total_score') + F('examination_participations__additional_score')) * 2))
    )
    return qs

谢谢你的帮助。

我发现30可以用F(“总分”)代替/2这是正确的,但这仍然给了我每行的计数。我需要整个查询集的计数。@cwhisperer如果只需要计数,请使用
…过滤器(ts\u gte=30).count()
并删除
.annotate(cnt\u suff=count('examition\u participations'))