Django:超过12个月的月度汇总问题

时间:2019-06-14 14:34:45

标签: python django django-queryset

这是我的模特

class Purchase(models.Model):
    date           = models.DateField(default=datetime.date.today,blank=False, null=True)
    total_purchase = models.DecimalField(max_digits=10,decimal_places=2,blank=True, null=True)

我想在上述模型中每月对total_purchase字段进行汇总。

我尝试了以下方法:

import datetime
import calendar
import collections
import dateutil
start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2019, 3, 31)
results = collections.OrderedDict()
result = Purchase.objects.filter(date__gte=start_date, date__lt=end_date).annotate(real_total = Case(When(Total_Purchase__isnull=True, then=0),default=F('Total_Purchase')))
date_cursor = start_date
z = 0
while date_cursor < end_date:
    month_partial_total = result.filter(date__month=date_cursor.month).aggregate(partial_total=Sum('real_total'))['partial_total']
    # results[date_cursor.month] = month_partial_total
    if month_partial_total == None:
        month_partial_total = int(0)
        e = month_partial_total
    else:
        e = month_partial_total

    z = z + e

    results[date_cursor.month] = z

    date_cursor += dateutil.relativedelta.relativedelta(months=1)

 return results

但是,如果我选择的日期范围超过十二个月,则结果仅显示十二个月。它计算出同一个月的总数。

**例如**

我要执行以下操作:

April      2800
May        2800
June       2800
July       2800
August     7800  #(2800 + 5000)
September  7800
October    13800 #(7800 + 6000)
November   13800
December   13800
january    14000   (13800+200)
february   14000
march      15000    (14000+1000)
April      18000   (15000+3000)
may        20000   (18000 + 2000)

在两个不同年份选择的月份。

如果我选择大于12个月的月份,它就会像这样出现:

April      20800    (taking both the years Aprils together)
May        22800     (taking both the years Mays together)
June       2800
July       2800
August     7800  #(2800 + 5000)
September  7800
October    13800 #(7800 + 6000)
November   13800
December   13800
january    14000   (13800+200)
february   14000
march      15000    (14000+1000)

请提供其他选择,以正确过滤12个月以上的日期并将其显示在列表视图中。

0 个答案:

没有答案