Django在连接上找到最大值

时间:2012-11-29 11:33:24

标签: python django postgresql django-models django-orm

我有两种模式:

class Source(models.Model):
    name = models.CharField(max_length=200)

class Data(models.Model):
    date = models.DateField(db_index=True)
    metric = models.IntegerField()
    source = models.ForeignKey(Source)

我想查找过去三天内没有任何数据点的所有来源。在PostgreSQL中,这是可行的:

select influence_source.src, max(influence_data.date) as max_date
from influence_data, influence_source
where influence_data.source_id = influence_source.id
group by influence_source.src
having max(influence_data.date) < now()::date - 7
order by max_date;

这是否可以使用Django的ORM?

我试过了:

>> Source.objects.raw("select influence_source.src, max(influence_data.date) as max_date from influence_data, influence_source where influence_data.source_id = influence_source.id group by influence_source.src having max(influence_data.date) < now()::date - 7 order by max_date")
<RawQuerySet: 'select influence_source.src, max(influence_data.date) as max_date from influence_data, influence_source where influence_data.source_id = influence_source.id group by influence_source.src having max(influence_data.date) < now()::date - 7 order by max_date'>
>> list(_)
InvalidQuery: Raw query must include the primary key

(添加主键提供DatabaseError: column "influence_source.id" must appear in the GROUP BY clause or be used in an aggregate function

我已阅读aggregation docs,但对我来说,如何进行此查询并不明显:

>> Source.objects.all().aggregate(Max('data__date'))
{'data__date__max': datetime.date(2012, 11, 16)} # a single result was not what I wanted

如何查找最近数据对象超过三天的所有源对象?我有很多数据,所以我想做一个单独的数据库查询,而不是迭代对象。

1 个答案:

答案 0 :(得分:0)

import datetime

three_days_ago = datetime.datetime.now() - datetime.timedelta(3)
Source.objects.annotate(max_date=Max('data__date')).exclude(max_date__gt=three_days_ago).order_by('max_date')