Django:通过查询计算列值的总和
我有一个模型:
class ItemPrice(models.Model):
price = models.DecimalField(max_digits=8, decimal_places=2)
# ...
我尝试用它来计算此查询集中的 price
总和:
items = ItemPrice.objects.all().annotate(Sum('price'))
此查询出了什么问题?或者是否有其他方法来计算 price
列的总和?
我知道这可以通过在查询集上使用 for 循环来完成,但我需要一个优雅的解决方案。
谢谢!
I have a model:
class ItemPrice(models.Model):
price = models.DecimalField(max_digits=8, decimal_places=2)
# ...
I tried this to calculate the sum of price
in this queryset:
items = ItemPrice.objects.all().annotate(Sum('price'))
What's wrong in this query? or is there any other way to calculate the Sum of price
column?
I know this can be done by using for loop on queryset but i need an elegant solution.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可能正在寻找
聚合
You're probably looking for
aggregate
使用
.aggregate(Sum('column'))['column__sum']
冷藏我的示例如下Use
.aggregate(Sum('column'))['column__sum']
reefer my example belowAnnotate 在结果中添加一个字段:
Aggregate 返回一个带有询问结果的字典:
Annotate adds a field to results:
Aggregate returns a dict with asked result:
使用cProfile分析器,我发现在我的开发环境中,对列表的值求和比使用
Sum()
聚合更有效(更快)。例如:
我在不同的上下文中对此进行了测试,似乎使用
aggregate
总是需要更长的时间才能产生相同的结果。尽管我怀疑使用它而不是对列表求和可能在内存方面有优势。Using cProfile profiler, I find that in my development environment, it is more efficient (faster) to sum the values of a list than to aggregate using
Sum()
.eg:
I tested this in different contexts and it seems like using
aggregate
takes always longer to produce the same result. Although I suspect there might be advantages memory-wise to use it instead of summing a list.以前的答案非常好,而且,您可以通过一行普通代码得到总数......
Previous answers are pretty well, also, you may get that total with a line of vanilla code...
您还可以通过以下方式获取总和:
将“金额”替换为要计算总和的模型中的列名称,并将“销售”替换为您的模型名称。
You could also get the sum this way:
Replace the 'amount' with the column name from your model you want to calculate the sum of and replace 'Sale' with your model name.
您需要使用 聚合() 和 Sum() 计算
price
列的总和,如下所示。 *使用 all() 的查询相当于不带 all() 的查询如下所示:然后,以下这些字典将在控制台上输出:
并且,您可以将 price 列的默认键
price__sum
更改为priceSum
,如下所示:然后,默认键更改如下:
You need to use aggregate() and Sum() to calculate the sum of
price
column as shown below. *The query with all() is equivalent to the query without all() as shown below:Then, these dictionaries below are outputted on console:
And, you can change the default key
price__sum
topriceSum
for price column as shown below:Then, the default key is changed as shown below: