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

标签 python django django-templates django-aggregation

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

View .py

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

    context = { 'total_invoice' : total_invoice }

html

{{total_invoice.total}}

这是我的代码,根据文档必须可以工作,并且正如我共享的链接上所建议的那样。不幸的是,它不起作用,我不知道是什么原因。 以下是我到目前为止所尝试过的。

尝试 1

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

print(total_invoice)

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

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

尝试 2(工作)

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

View .py

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

    context = { 'total' : total }

html

{{total.total}}

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

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

我不知道到底发生了什么。

任何人都可以帮我解决这个问题吗? 谢谢

最佳答案

如果进行聚合,您将获得一个字典。事实上,你会看到:

{'total': 70000}

您可以使用 {{ <i>variable_name</i>.<i>key</i> }} 访问与键对应的值在 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> }}

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

    …
    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> }}

关于python - Django 聚合。如何将其值渲染到模板中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468057/

相关文章:

python - 如何将文件中的每个字符转换为其 ASCII 数字? Python

python - 在实时服务器上开始使用 Pyramid

python - Django 注释与 select_related

django - rabbitmq+celery 内存泄漏?

css - django 在背景图像上返回 403 Forbidden

python - Jinja2 异常处理

python - splash lua脚本做多次点击访问

python - 如何用 pandas 和 matplotlib 绘制两个分类(名义)系列之间的比较

python - Django模板问题: how to output just the text if the variable has html in it?

python - Django 模板 - 在哪里编码以查找此特定模板?