django - 如何在 Django 中使用 postgresql 'interval'?

标签 django postgresql intervals

这是我的 PostgreSQL 语句。

select round(sum("amount") filter(where "date">=now()-interval '12 months')/12,0) as avg_12month from "amountTab"

如何在 Django 中使用它?

我有一个名为“Devc”的对象,其属性为“日期”。

我想获取过去 12 个月内特定数据的总和,而不是过去 365 天。

最佳答案

您可以试试这个来获取过去 12 个月内的数据。

today= datetime.now()
current_month_first_day = today.replace(day = 1)
previous_month_last_day = current_month_first_day - timedelta(days = 1)
past_12_month_first_day = previous_month_last_day - timedelta(days = 360)
past_12_month_first_day = past_12_month_first_day.replace(day = 1)

 past_12_month_avg = Devc.objects.filter(date__range=(past_12_month_first_day,current_month_first_day)).aggregate(Sum('amount'))['amount']

关于django - 如何在 Django 中使用 postgresql 'interval'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404517/

相关文章:

django - 为什么 Django 更喜欢 Postgresql?

python - 无法访问属于任何人的媒体文件 :nobody

postgresql - Docker-Compose Postgresql 导入转储

计算最佳定时器间隔 (timer_settime)

algorithm - 使用散列计算整数数组中某个模式出现的次数

java - Android:间隔调用方法来检索最新的位置坐标

python - Django Tastypie 不使用 ManyToManyField 更新资源

postgresql - Postgres ltree 多路径

mysql - 如何从表中的字段获取值

python - 切片查询集与切片 __in 子句中使用的列表相同吗?无法理解这种行为