Django 对除查询项之外的模型实例进行注释使用

发布于 2024-11-17 05:29:02 字数 555 浏览 3 评论 0原文

我有一个查询,

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

em[0].overall_value

如您所见,我想要对 employer 具有 id = 1 的所有 companyreview 对象的 overallRating 字段进行求和

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

我怎样才能像这样实现这个查询

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

谢谢

I have a query such that

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

em[0].overall_value

As you see I want to sum of overallRating field of all companyreview objects whose employer has id = 1.

The query above does what I want but I am sure that there is a way to get the sum from an Employer instance.

How can I implement this query like

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

?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

明明#如月 2024-11-24 05:29:02

使用聚合

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()    

Use aggregate:

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

For:

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

class CompanyReview(models.Model): 
     employer = models.ForeignKey(Employer)
     overall_rating = models.IntegerField()    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文