简体   繁体   English

Django / Postgres按汇总分组

[英]Django / Postgres Group By Aggregate

I've have an issue regarding queries with a group by clause. 我有一个关于带有group by子句的查询的问题。 Lets assume I have the following Django-Model: 假设我有以下Django模型:

class SomeModel(models.Model):
    date = models.DateField()
    value = models.FloatField()
    relation = models.ForeignKey('OtherModel')

If I want to do a query where I group SomeModel instances by OtherModel and annotate the latest date: 如果要执行查询,在其中我按OtherModel分组SomeModel实例并注释最新日期:

SomeModel.objects.values('relation').annotate(Max('date'))

This is all great, but as soon as I want to add a filter on the already annotated queryset I am getting nowhere: 一切都很好,但是一旦我想在已经注释的查询集上添加一个过滤器,我将无处可去:

SomeModel.objects.values('relation').annotate(Max('date')).filter(value__gt=0)

This would indeed filter out all the value != 0, however I only want it after the annotations took place. 这确实会过滤掉所有值!= 0,但是我只希望在注释发生后才使用它。 If the latest date of a relation has the value 0, I want it to be filtered out! 如果关系的最新日期值为0,我希望将其过滤掉!

You need to add the value in the annotate filed and then you can filter over it. 您需要在注释字段中添加值,然后可以对其进行过滤。 Your ORM query becomes 您的ORM查询变为

SomeModel.objects.values('relation').annotate(Max('date'), value=F('value')).filter(value__gt=0)

This should give the value you require 这应该提供您需要的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM