I have the following two annotated QuerySets which I have generated separately by extracting this_wk
and prev_wk
from a data set, then performing the annotation. I would like to merge them together before returning them.
data = {
'this_wk': QuerySet([{'this_total': 3, 'dept': 2},
{'this_total': 2, 'dept': 1},
{'this_total': 1, 'dept': 3}]),
'prev_wk': QuerySet([{'prev_total': 2, 'dept': 3}])}
Expected:
QuerySet([{'this_total': 3, 'prev_total': None, 'dept': 2},
{'this_total': 2, 'prev_total': None, 'dept': 1},
{'this_total': 1, 'prev_total': 2, 'dept': 3}]),
Alternatively, is there a way of aggregating this directly so that I go straight from a set of items with date fields? Here's how I am currently generating the two QuerySets:
previous_items = Widget.objects.filter(start__gte=prev_start).filter(start__lte=prev_end)
prev_ranking = previous_items.values('dept').annotate(prev_total=Count('dept'))
this_items = Widget.objects.filter(start__gte=this_start
).filter(start__lte=this_end)
this_ranking = this_items.values('dept'
).annotate(this_total=Count('dept')
).order_by('-this_total')
Is there a way to chain these two annotations together so that I end up with a single QuerySet grouped and ranked for each Dept
depending on how many Widgets
it was used by this week, but also with an added field that says how many Widgets
it was used by the previous week?
I'm thinking something like this:
items = Widget.objects.filter(start__gte=prev_start
).filter(start__lte=this_end
).annotate(prev_total=Count('dept') # can I restrict this to the previous week?
).annotate(this_total=Count('dept') # can I restrict this to the current week?
).order_by('-this_total')