Thursday, July 26, 2018

[Question] Django 2 - how to sum values based on filter and group by Year-Month

I have the following table:

2018-01-01      10
2018-01-15      20
2018-01-31      30
2018-02-01      10
2018-03-01      10
2018-03-20      20

I need to Sum() the values filtering it with 
1 - sum(values) where date < first day of the month
2 - sum(values) where date < last day of the month

Expected result(something like that):
[
 {'year-month': '2018-01'}, {'sum_before_month_day_one': 0}, {'sum_before_last_month_day': 60},
 {'year-month': '2018-02'}, {'sum_before_month_day_one': 60}, {'sum_before_last_month_day': 70},
 {'year-month': '2018-03'}, {'sum_before_month_day_one': 70}, {'sum_before_last_month_day': 100},
]

So far I manage to sum values and group by month:

In [12]: result = Sale.objects \
    ...:     .annotate(date=TruncMonth('event_date')) \
    ...:     .values('date') \
    ...:     .annotate(quantity=Sum('quantity')) \
    ...:     .values('date', 'quantity') \
    ...:     .order_by('date')

In [13]: for i in result: print(i)

{'date': datetime.date(2018, 1, 1), 'quantity': 60.0}
{'date': datetime.date(2018, 2, 1), 'quantity': 10.0}
{'date': datetime.date(2018, 3, 1), 'quantity': 30.0}

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a57a7058-ea08-4909-8e98-c678aa9969cc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment