【发布时间】:2018-04-18 22:56:38
【问题描述】:
我正在使用具有日期、组和标识符的模型。 我想为每个组检索最小日期值的 id。
我的模特:
class MyModel(models.Model):
group = models.ForeignKey('myapp.Group')
date = models.DateTimeField(blank=True, null=True)
目标是检索这个:
[
(u'group1', datetime.date(2016, 1, 23), 15 <- Id of the minimum date for group1),
(u'group2', datetime.date(2015, 6, 25), 314 <- Id of the minimum date for group2),
...
]
我尝试了以下方法:
MyModel.objects.values_list('group').annotate(Min('date')).order_by('group')
这很好用,但只给了我日期:
[
(u'group1', datetime.date(2016, 1, 23)),
(u'group2', datetime.date(2015, 6, 25)),
(u'group3', datetime.date(2015, 6, 26))
...
]
在不破坏 SQL 中的分组子句的情况下,我找不到将 id 添加到这些元组的方法。 我尝试了 where date = min(date),但是 where 子句中禁止聚合。
【问题讨论】:
标签: django django-queryset aggregation