【问题标题】:Django find max on a joinDjango在加入时找到最大值
【发布时间】:2012-11-17 11:20:40
【问题描述】:

我有两个模型:

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

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

【问题讨论】:

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


    【解决方案1】:
    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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 2013-09-12
      • 2012-06-21
      • 1970-01-01
      • 2011-07-12
      • 2021-12-17
      相关资源
      最近更新 更多