Django Aggregation: Summation of Multiplication of two fields(Django聚合:两个字段相乘的总和)
问题描述
我有一个类似这样的模型:
I have a model something like this:
class Task(models.Model):
progress = models.PositiveIntegerField()
estimated_days = models.PositiveIntegerField()
现在我想在数据库级别进行计算Sum(progress *estimated_days)
.使用 Django Aggregation 我可以得到每个字段的总和,但不能得到字段乘法的总和.
Now I would like to do a calculation Sum(progress * estimated_days)
on the database level. Using Django Aggregation I can have the sum for each field but not the summation of multiplication of fields.
推荐答案
更新: for Django >= 1.8 请按照@kmmbvnr 提供的答案
Update: for Django >= 1.8 please follow the answer provided by @kmmbvnr
可以使用 Django ORM:
it's possible using Django ORM:
这是你应该做的:
from django.db.models import Sum
total = ( Task.objects
.filter(your-filter-here)
.aggregate(
total=Sum('progress', field="progress*estimated_days")
)['total']
)
注意:如果两个字段的类型不同,请说 integer
&float
,要返回的类型应该作为Sum
Note: if the two fields are of different types, say integer
& float
, the type you want to return should be passed as the first parameter of Sum
这是一个迟到的答案,但我想它会帮助寻找相同的人.
It's a late answer, but I guess it'll help someone looking for the same.
这篇关于Django聚合:两个字段相乘的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django聚合:两个字段相乘的总和


- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01