This is model:
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)
I want to perform a month wise calculation of "total_purchase" within a specific daterange in such a way that if there is no purchase in a month the total purchase should be the previous month purchase value And if there is purchase in two months then total purchase will the addition of those two...
Example:
Suppose the date range given by user is from month of April to November.
If there is a Purchase of $2800 in month of April and $5000 in month of August and $6000 in month of October.
Then the output will be like this:
April 2800
May 2800
June 2800
July 2800
August 7800 #(2800 + 5000)
September 7800
October 13800 #(7800 + 6000)
November 13800
Any idea how to perform this in django queries?
Thank you
According to the answer given by Mr.Raydel Miranda. I have done the following
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('tal_Purchase')))
date_cursor = start_date
while date_cursor < end_date:
month_partial_total = result.filter(date__month=date_cursor.month).agggate(partial_total=Sum('real_total'))['partial_total']
results[date_cursor.month] = month_partial_total
if month_partial_total == None:
month_partial_total = int(0)
else:
month_partial_total = month_partial_total
date_cursor += dateutil.relativedelta.relativedelta(months=1)
return results
But now the output is coming like this(from the example above):
April 2800
May 0
June 0
July 0
August 5000
September 0
October 6000
November 0
Do anyone have any idea how to add between the months... I want to do something like
e = month_partial_total + month_partial_total.next
I want to add the next iteration value of every month_partial_total. I think this will solve my problem..
Any idea anyone how to perform this in django?
Thank you