Django 聚合。如何将其值渲染到模板中?

Django aggregation. How to render its value into the template?

我遇到了一个我根本无法理解的最奇怪的问题。好吧,我一直在关注 ,但没有任何帮助。 正如问题所说,我只想将结果渲染到模板中。下面是我的代码。

Views.py

...
    invoice = lead.invoice_set.all()
    total_invoice = invoice.aggregate(total=Sum('amount'))

    context = { 'total_invoice' : total_invoice }

html

{{total_invoice.total}}

这是我的代码,根据文档,它必须正常工作,正如它在我分享的 link 中所建议的那样。不幸的是,它不工作我不知道是什么原因。 以下是我迄今为止尝试过的方法。

尝试 1

当我尝试将其打印到终端时,它给我带来了一本字典。例如。

print(total_invoice)

prints on terminal...
{'total': 70000}

这很好理解。现在我想提取值,这可以通过简单的 {{total_invoice.total}} 来完成。但它在模板上没有显示任何内容。

尝试 2(工作)

因为我尝试了不同的方法来将值呈现到模板中,所以我遇到了这个奇怪的解决方案。我不知道这是怎么回事。 我在这里所做的与 TRY 1 不同的地方只是将变量名称 (total_invoice) 更改为 (total) 并且它工作得很好。这是方法。

Views.py

    invoice = lead.invoice_set.all()
    total = invoice.aggregate(total=Sum('amount'))

    context = { 'total' : total }

html

{{total.total}}

只需将变量名称更改为 total,即可完美运行。但后来我认为名称应该相同,但事实并非如此,所以我尝试为两个变量指定相同的名称,但这次是 'total' 之外的其他名称,但它再次不起作用。例如

...
total_invoice = invoice.aggregate(total_invoice =Sum('amount'))

到底是怎么回事,我不知道。

谁能帮我解决这个问题。 谢谢

如果你聚合,你会得到一个词典。确实,你看:

{'total': 70000}

您可以使用 {{ <i>variable_name</i>.<i>key[=40= 访问对应于键的值] }} 在 Django 模板中。

所以如果你通过它:

    …
    total_invoice = invoice.aggregate(<b>total_invoice</b>=Sum('amount'))
    …
    render(request, 'some_template.html', {<i>'total_invoice'</i>: total_invoice })

然后在模板中渲染它:

{{ <i>total_invoice</i>.<b>total_invoice</b> }}

点之前的部分是指变量名:字典中的名字(斜体),第二部分是字典中的键(粗体)。

如果您因此通过名为 total 的变量传递它:

    …
    total_invoice = invoice.aggregate(<b>total_invoice</b>=Sum('amount'))
    …
    render(request, 'some_template.html', {<i>'total'</i>: total_invoice })

你渲染它:

{{ <i>total</i>.<b>total_invoice</b> }}

然而,在视图中解压字典可能更明智,因此将总数作为一个变量传递:

    …
    total_invoice = invoice.aggregate(<b>total</b>=Sum('amount'))<b>['total']</b>
    …
    render(request, 'some_template.html', {<i>'total_invoice'</i>: total_invoice })

然后渲染它:

{{ <i>total_invoice</i> }}