Django聚合:仅求和返回值?

Django Aggregation: Sum return value only?(Django聚合:仅求和返回值?)
本文介绍了Django聚合:仅求和返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个已支付价值的列表,并希望显示已支付的总金额.我使用聚合和 Sum 一起计算值.问题是,我只想打印总值,但聚合打印出: {'amount__sum': 480.0} (480.0 是增加的总值.

I have a list of values paid and want to display the total paid. I have used aggregation and Sum to calculate the values together. The problem is,I just want the total value printed out, but aggregation prints out: {'amount__sum': 480.0} (480.0 being the total value added.

在我看来,我有:

    from django.db.models import Sum

    total_paid = Payment.objects.all.aggregate(Sum('amount'))

为了在页面上显示值,我有一个带有以下内容的 mako 模板:

And to show the value on the page, I have a mako template with the following:

    <p><strong>Total Paid:</strong> ${total_paid}</p>

如何让它显示 480.0 而不是 {'amount__sum': 480.0}?

How would I get it to show 480.0 instead of {'amount__sum': 480.0}?

推荐答案

我不相信有办法只获得价值.

I don't believe there is a way to get only the value.

您可以在模板中执行 ${{ total_paid.amount__sum }}.或者在你的视图中执行 total_paid = Payment.objects.all().aggregate(Sum('amount')).get('amount__sum', 0.00).

You could just do ${{ total_paid.amount__sum }} in your template. Or do total_paid = Payment.objects.all().aggregate(Sum('amount')).get('amount__sum', 0.00) in your view.

编辑

正如其他人指出的那样,.aggregate() 将始终返回一个字典,其中包含来自聚合的所有键,因此在 .get() 上执行结果是不必要的.但是,如果查询集为空,则每个聚合值将是 None.因此,根据您的代码,如果您期望浮动,您可以这样做:

As others have pointed out, .aggregate() will always return a dictionary with all of the keys from the aggregates present, so doing .get() on the result is not necessary. However, if the queryset is empty, each aggregate value would be None. So depending on your code, if you are expecting a float, you could do:

total_paid = Payment.objects.all().aggregate(Sum('amount'))['amount__sum'] 或 0.00

这篇关于Django聚合:仅求和返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)