我创建了一个函数来从数据库获取一些日期,进行一些计算并将其显示在 HTML 文件中。但是我无法仅从视图中获取值。
def list_pay(request):
item = Pay.objects.all()
# Quantidades
q_total = Pay.objects.all().count
q_open = Pay.objects.filter(status=0).count
q_paied = Pay.objects.filter(status=1).count
# Soma dos valores
v_total = Pay.objects.aggregate(Sum('value'))
v_open = Pay.objects.filter(status=0).aggregate(Sum('value'))
v_paied = Pay.objects.filter(status=1).aggregate(Sum('value'))
data = {
'item':item,
'v_total':v_total,
'v_open':v_open,
'v_paied':v_paied,
'q_total':q_total,
'q_open':q_open,
'q_paied':q_paied
}
return render(request, 'pay/list_pay.html', data)
<div class="row d-flex justify-content-center">
<h3 class="mb-3 mt-3">Lista <span class="text-success">de pagamentos</span></h3>
<div class="col m-3 p-3">
<label>Total de boletos</label>
<h1 class="text-primary"> {{ q_total }}</h1>
<h1 class="text-primary"> {{ v_total }}</h1>
</div>
<div class="col m-3 p-3">
<span>Quantidade de boletos</span>
<h1 class="text-success">{{ q_paied }}</h1>
<h1 class="text-success">{{ v_paied }}</h1>
</div>
<div class="col m-3 p-3">
<span>Quantidade de boletos</span>
<h1 class="text-danger">{{ q_open }}</h1>
<h1 class="text-danger">{{ v_open }}</h1>
</div>
</div>
当前加载的值 = {'value__sum': 1831}。预期产出 = 1831
我已经尝试过 .values() 并将字典转换为列表和其他格式。
执行查找,因此:
<h1 class="text-success">{{ v_paied.value__sum }}</h1>
或者,您可以在视图中执行查找:
v_paied = Pay.objects.filter(status=1).aggregate(Sum('value'))['value__sum']
话虽这么说,您当前正在执行多个查询,这些查询可以组合在一个 SQL 查询中。
您应该能够通过类似的内容在单个聚合查询中获取所有这些内容
def list_pay(request):
pay_items = Pay.objects.all()
aggregate_data = pay_items.aggregate(
q_open=Count("id", filter=Q(status=0)),
q_paied=Count("id", filter=Q(status=1)),
q_total=Count("id"),
v_open=Sum("value", filter=Q(status=0)),
v_paied=Sum("value", filter=Q(status=1)),
v_total=Sum("value"),
)
data = {
"item": pay_items,
**aggregate_data,
}
return render(request, "pay/list_pay.html", data)