1

我有一个这样的查询

em =Employer.objects.filter(id=1).annotate(overall_value = Sum('companyreview__overallRating'))

em[0].overall_value

如您所见,我想对overallRating所有具有.companyreviewemployerid = 1

上面的查询可以满足我的要求,但我确信有一种方法可以从Employer实例中获取总和。

我怎样才能实现这个查询

em =Employer.objects.get(id=1)
rate = em.companyreview_set.all().annotate(overall_value = Sum('overallRating'))
rate.overall_value

?

谢谢

4

1 回答 1

2

使用aggregate

e.companyreview_set.aggregate(overall_value = Sum('overall_rating'))

为了:

class Employer(models.Model): 
     name = models.CharField(max_length=100)

class CompanyReview(models.Model): 
     employer = models.ForeignKey(Employer)
     overall_rating = models.IntegerField()    
于 2011-06-24T08:01:45.847 回答