問題描述
我有一個已支付價值的列表,并希望顯示已支付的總金額.我使用聚合和 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'))
為了在頁面上顯示值,我有一個帶有以下內(nèi)容的 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.
您可以在模板中執(zhí)行 ${{ total_paid.amount__sum }}
.或者在你的視圖中執(zhí)行 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()
上執(zhí)行結(jié)果是不必要的.但是,如果查詢集為空,則每個聚合值將是 None
.因此,根據(jù)您的代碼,如果您期望浮動,您可以這樣做:
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
這篇關(guān)于Django聚合:僅求和返回值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!