Django 3.2.9
db:(PostgreSQL(14.0
型号
class InventoryForecast(models.Model):
count = models.IntegerField()
forecast_for = models.DateTimeField(null=False)
forecasted_at = models.DateTimeField(null=False)
数据
id | 计数 | forecast_forforecast _at | |
---|---|---|---|
8 | 40910 | 2022-10-10 11:00 | 2022-09-04 12:00 |
9 | 40909 | 2022-10-10 11:00 | 2022-09-05 12:00 |
10 | 50202 | 2022-10-10 11:00 | 2022-09-06 12:00(最新预测( |
11 | 50301 | 2022-10-10 12:00 | 2022-09-04 12:00 |
12 | 50200 | 2022-10-10 12:00 | 2022-09-05 12:00 |
13 | 50309 | 2022-10-10 12:00 | 2022-09-06 12:00(最新预测( |
此解决方案注释新字段forecast_for_hour
,该字段使用TruncHour
从forecast_for
时间戳创建整个小时,然后按forecast_for_hour
升序和forecasted_at
降序排序,将它们分组。由于您使用的是PostgreSQL,因此我们可以在forecast_for_hour
上调用distinct,由于按forecasted_at
降序排序,它采用了最新的预测
qs = (
InventoryForecast.objects
.annotate(forecast_for_hour=TruncHour('forecast_for'))
.order_by('forecast_for_hour', '-forecasted_at')
.distinct('forecast_for_hour')
)