如何在视图中对Django日期范围结果求和?



我想在日期范围查询搜索中添加所有金额字段。我有一个收入模型,其中包括日期和金额字段。每当用户在两个日期之间进行选择时,我希望查询结果的金额字段添加为total。以下是我尝试过的:

def SearchIncomeRange(request):
listIncome = Income.objects.all()
searchForm = IncomeSearchForm(request.POST or None)
if request.method == 'POST':
listIncome = Income.objects.filter(
description__icontains=searchForm['description'].value(),
date__range=[
searchForm['start_date'].value(),
searchForm['end_date'].value()
]
)
else:
searchForm = IncomeSearchForm()
paginator = Paginator(listIncome, 5)
page = request.GET.get('page')
paged_income = paginator.get_page(page)
context = {

'searchForm':searchForm,
}
return render(request, 'cashier/search_income_range.html', context)

我能够得到正确的搜索结果,但是得到总数,我不知道如何在上面的查询中使用SUM并在分页中传递总数。所以应该有人帮帮我。由于

from django.db.models import Sum
total_amount = listIncome.aggregate(total=Sum('amount'))

其中listIncome是您的查询集

编辑:

如果您应用了任何过滤器,则应该在分页中传递带有过滤的查询集的查询集。

我修改了你写的代码,但是你可以用一种好的方式写这段代码。

def SearchIncomeRange(request):
listIncome = Income.objects.all()
searchForm = IncomeSearchForm(request.POST or None)
if request.method == 'POST':
# you can get filter value by your form data
post_data = request.POST
description = post_data['description']
start_date = post_data['start_date']
end_date = post_data['end_date']
else:
# you can get filter value by your query params
query_params = request.GET
description = query_params.get('description')
start_date = query_params.get('start_date')
end_date = query_params.get('end_date')
# Apply filter before pagination
listIncome = listIncome.filter(
description__icontains=description,
date__range=[start_date, end_date]
)

# calculate total_amount 
total_amount = listIncome.aggregate(total=Sum('amount'))
paginator = Paginator(listIncome, 5)
page = request.GET.get('page')
paged_income = paginator.get_page(page)
# you can access total_amount in template by passing in context data
context = {
'searchForm':searchForm,
'total_amount': total_amount
}
return render(request, 'cashier/search_income_range.html', context)

最新更新