0

我有两个模型:

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

我已经阅读了聚合文档,但对我来说如何执行此查询并不明显:

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

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

4

1 回答 1

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')
于 2012-12-03T15:09:25.333 回答