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

2024-09-29 23:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

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


Tags: getdateobjectsvaluerequestpagerangedescription
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:58
from django.db.models import Sum

total_amount = listIncome.aggregate(total=Sum('amount'))

你的查询集在哪里

编辑:

如果应用了任何筛选器,则应在分页中使用筛选的queryset传递queryset

我更改了您编写的代码,但您可以用一种很好的方式编写此代码。

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)

相关问题 更多 >

    热门问题