Reputation: 59
Filter with the date and find the sum of the range, not the total of all the objects,example, from January 1 until January 2 or from February 1 to February 20, each range.
This is my code:
def orecerca(request):
qs = Ore.objects.filter(user=request.user)
sum = Ore.objects.filter(user=request.user).aggregate(totals=(Sum('oret')))
nomecognome = request.GET.get('nomecognome')
date_min = request.GET.get('date_min')
date_max = request.GET.get('date_max')
if is_valid_queryparam(nomecognome):
qs = qs.filter(nomecognome=nomecognome)
if is_valid_queryparam(date_min):
qs = qs.filter(data__gte=date_min)
if is_valid_queryparam(date_max):
qs = qs.filter(data__lte=date_max)
context = {
'ore': qs,
'sum': sum,
}
return render(request, "guarda.html", context,)
Upvotes: 3
Views: 90
Reputation: 477666
You can postpone aggregating until you constructed the filtered queryset, like:
def orecerca(request):
qs = Ore.objects.filter(user=request.user)
nomecognome = request.GET.get('nomecognome')
date_min = request.GET.get('date_min')
date_max = request.GET.get('date_max')
if is_valid_queryparam(nomecognome):
qs = qs.filter(nomecognome=nomecognome)
if is_valid_queryparam(date_min):
qs = qs.filter(data__gte=date_min)
if is_valid_queryparam(date_max):
qs = qs.filter(data__lte=date_max)
total = qs.aggregate(totals=(Sum('oret')))
context = {
'ore': qs,
'sum': total,
}
return render(request, "guarda.html", context,)
Upvotes: 1