使用Django模型每小时查找一条记录,以及另一个时间戳中的最新记录


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)

数据

forecast_for
id计数forecast _at
8409102022-10-10 11:002022-09-04 12:00
9409092022-10-10 11:002022-09-05 12:00
10502022022-10-10 11:002022-09-06 12:00(最新预测(
11503012022-10-10 12:002022-09-04 12:00
12502002022-10-10 12:002022-09-05 12:00
13503092022-10-10 12:002022-09-06 12:00(最新预测(

此解决方案注释新字段forecast_for_hour,该字段使用TruncHourforecast_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')
)

相关内容

最新更新