问题描述
我有一个类似这样的模型:
I have a model something like this:
class Task(models.Model):
progress = models.PositiveIntegerField()
estimated_days = models.PositiveIntegerField()
现在我想在数据库级别做一个计算Sum(progress *ested_days)
.使用 Django 聚合,我可以得到每个字段的总和,但不能得到字段乘法的总和.
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.
推荐答案
更新: 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 聚合:两个字段相乘的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!