如何在Django中使用posgresql'interval'?

时间:2018-11-21 02:31:10

标签: django postgresql intervals

这是我的PostgreSQL语句。

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

如何在Django中使用它?

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

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

1 个答案:

答案 0 :(得分:1)

您可以尝试在past 12 months中获取数据。

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']