我有一个类似这样的模型:
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聚合:两个字段相乘的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!