When I query my database I get the same entry three times with three different counts. In the result list I would like to get just one entry showing the sum of these counts.
What I would like to display is the total for a specific period.
In my query I enter the dates (from - until), a metric_type, a data_type and a year of publication.
For instance I on the website when I enter
from 201903 until 201905
I retrieve three titles that have been accessed in this period as well as how many times they have been accessed.
Title, Publisher, DOI, data_type,YOP,[some other stuff] Counts
Title A publisherA 1234 Article, 2006, [some_other_stuff], 3
Title A publisherA 1234 Article, 2006, [some_other_stuff], 5
Title A publisherA 1234 Article, 2006, [some_other_stuff], 3
What I would need is something like
Title, publisher, DOI, data_type, YOP, [some_other_stuff], Total period
Title A, publisherA 1234 Article, 2006, [some_other_stuff], 11
In views.py I have the following code:
q_report = Q()
var0 = self.request.GET.get("period1", "")
var1 = self.request.GET.get("period2", "")
var2 = self.request.GET.get("metric_type", "")
var3 = self.request.GET.get("data_type", "")
var4 = self.request.GET.get("YOP", "")
if var0:
q_report = q_report & (Q(month__gte=var0) & Q(month__lte=var1) )
#q_report_count = q_report_count & (Count(month__gte=var0) & Count(month__lte=var1) )
if var2:
q_report = q_report & (Q(metric_type=var2))
#q_report_count = q_report_count & (Q(metric_type=var2))
if var3:
q_report = q_report & (Q(data_type=var3))
if var4:
q_report = q_report & (Q(YOP=var4))
If I use
qs = self.model.objects.filter(q_report).select_related()
I will get back the three entries
The result is
<QuerySet [<Model: Title A>, <Model: Title A>, <Model: Title A>]>
I can easily calculate the total by using
total = self.model.objects.aggregate(total=Sum('counts', filter=q_report))
The result is
{total : 11.0}
But ideally I need to get the other values as well
Right now, I cannot see how I can get the two together, i.e. something like
<QuerySet [<Model: {'title':Title A, 'total':11}>, Model: {'title':Title B, 'total':7}>]
I don't even know whether this is possible or desired. But I need to return the queryset and the total.
Can anyone help? Thanks.