Django注释总和 [英] Django Annotate Sum
问题描述
我正在尝试为查询集中具有几行的一列获取一个简单的总和。我的直接问题是(a)如何设置 get_queryset()
包括列的总和,以及(b)如何访问模板中的该元素?遵循此问题:
I'm trying to get a simple sum for a column with several rows in a queryset. My direct question is (a) how do I set get_queryset()
to include a sum of a column and (b) how do I access that element in a template? Following this question:
#models.py
class ItemPrice( models.Model ):
price = models.DecimalField ( max_digits = 8, decimal_places=2 )
....
有两个答案-一个使用我不相信会返回查询集的 .aggregate()
方法和我所使用的 .annotate()
方法相信会将一个项目添加到查询集。
There are two answers provided - one using the .aggregate()
method which I don't believe returns a queryset and .annotate()
method which I believe appends an item to the queryset.
因此,我希望以下内容在该视图中将另一个项目添加到对象列表:
So, I would have expected that the following would add another item to the object list in this view:
#views.py
def get_queryset(self):
# generate table and filter down to a subquery.
queryset = ItemPrice.objects.filter(<some_filter>)
# sum the price for each row in the subquery.
queryset = queryset.annotate(totals=Sum('price'))
return queryset
然后在模板中,我可以像这样遍历对象列表:
Then in the the Template, I would be able to iterate through the object list like this:
#template.html
{% for item in object_list %}
{{ item }}
{% endfor %}
期望其中一项(最后一项?)将是 price_sum
,余额可以作为 price_sum.price
。
With the expectation that one of the items (the last item?) would be price_sum
and that the balance could be accessed as price_sum.price
.
但是,当我在模板中添加以下内容时,我会获得每个订单项的价格-没有总结。
However, when i add the following to my template, I get the prices for each line item - no summation.
{% for item in object_list %}
{{ item.totals }}
{% endfor %}
但是,我无法访问该项目。我不知道问题是 get_queryset()
的视图修改还是在模板中?
But, I can't access the item. I don't know if the problem is the view modification of the get_queryset()
or if it's in the template?
推荐答案
如果要将数据添加到模板
if you want to add data to the template
queryset = ItemPrice.objects.filter(<your_filter>)
totals = queryset.aggregate(sum=Sum('price').get('sum')
context = {
'object_list': queryset,
'totals': totals,
}
render(request, '<name_of_your_template>.html', context)
并在您的模板中
{% for item in object_list %}
# price of item
{{ item.price }}
{% endfor %}
# total price
{{ totals }}
这篇关于Django注释总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!