【发布时间】:2018-05-09 05:45:24
【问题描述】:
我正在尝试为查询集中包含多行的列获取简单的总和。我的直接问题是(a)我如何设置get_queryset() 以包含一列的总和以及(b)我如何在模板中访问该元素?关注this问题:
#models.py
class ItemPrice( models.Model ):
price = models.DecimalField ( max_digits = 8, decimal_places=2 )
....
提供了两个答案 - 一个使用 .aggregate() 方法,我不相信它会返回一个查询集,而 .annotate() 方法我相信它会将一个项目附加到查询集。
所以,我希望以下内容会在此视图的对象列表中添加另一个项目:
#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
然后在模板中,我将能够像这样遍历对象列表:
#template.html
{% for item in object_list %}
{{ item }}
{% endfor %}
期望其中一项(最后一项?)是price_sum,并且余额可以作为price_sum.price访问。
但是,当我将以下内容添加到我的模板时,我会得到每个行项目的价格 - 没有总和。
{% for item in object_list %}
{{ item.totals }}
{% endfor %}
但是,我无法访问该项目。不知道是get_queryset()的视图修改问题还是模板里面的问题?
【问题讨论】:
-
首先,您可以将两个查询结合起来,无需在两行中写入。
queryset = ItemPrice.objects.filter(<some_filter>).annotate(totals=Sum('price'))如果您希望显示商品的总价格,那么您可以使用模板标签。跨度> -
感谢@AbiWaqas,我试图遵循原始问题。我的原始代码完全按照您的建议编写 - 但它仍然没有产生我期望的
annotate(Sum)结果。
标签: python django python-3.x