Is it possible to annotate .sum()
s over multiple date ranges in one QuerySet
Ie, basically combining these, so each object has the sum for each date range.
query_set_week = DailyReports.objects.filter(
date__range=('2018-08-27', '2018-08-31')) \
.select_related('profile') \
.values('profile__user_id') \
.annotate(premium=Sum('total_field'),
first_name=F('profile__user__first_name'),
last_name=F('profile__user__last_name') \
.order_by('profile__agent_code')
query_set_year = DailyReports.objects.filter(
date__range=('2018-01-01', '2018-08-31')) \
.select_related('profile') \
.values('profile__user_id') \
.annotate(premium=Sum('total_field'),
first_name=F('profile__user__first_name'),
last_name=F('profile__user__last_name') \
.order_by('profile__agent_code')
Both work individually, but it's difficult to loop through and display the data (user - week total - year total, for example), because someone may have a result in the year filter, but not in the week filter.
Edit: I'm currently able to accomplish my goal using .raw()
with a massive SQL statement, but I figured there was a more Pythonic way to do it.