繁体   English   中英

Django 注释总和

[英]Django Annotate Sum

我正在尝试为查询集中有几行的列获得一个简单的总和。 我的直接问题是 (a) 如何设置get_queryset()以包含一列的总和以及 (b) 如何在模板中访问该元素? 按照这个问题:

#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()的视图修改的问题还是模板中的问题?

如果你会使用:

ItemPrice.objects.filter(<some_filter>).annotate(totals=Sum('price'))

总计将始终与“价格”相同

注释(关于总和)使用如下:

如果你有这些模型:

class ItemPrice( models.Model ):
    price = models.DecimalField ( max_digits = 8, decimal_places=2 )
    other_model = models.ForeignKey(
          to=OtherModel, 
          related_name="item_prices", 
          on_delete=models.SET_NULL
    )

# related_name - if I set related_name I can use like this
# other_model_object.item_prices.all() - this code return all 
# ItemPrices with other_model_id=other_model_object.id

class OtherModel(models.Model):
    some_field = models.CharField(max_lenght=256)

并且您想要所有具有指向一个 OtherModel 的外键的 ItemPrices 的所有价格,您应该使用以下代码:

queryset = OtherModel.objects.annotate(
       total_prices=Sum('item_prices__price')
).filter(<your_filters>)

之后你可以使用:

for obj in queryset:
    print(obj.total_prices)

或者,如果您需要所有价格的总和,您应该使用聚合

ItemPrices.objects.aggregate(all_sum=Sum('price'))

这段代码像这样返回字典(或类似的东西,我记不太清了)

{'all_sum': 1250}

all_sum - 数据库中表中所有对象的总和

如果要将数据添加到模板

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM