python - Django 聚合 : Summation of Multiplication of two fields

标签 python django django-models django-queryset django-orm

我有一个类似这样的模型:

class Task(models.Model):
    progress = models.PositiveIntegerField()
    estimated_days = models.PositiveIntegerField()

现在我想在数据库级别进行计算Sum(progress *estimated_days)。使用 Django Aggregation 我可以得到每个字段的总和,但不能得到字段乘法的总和。

最佳答案

使用 Django 1.8 及更高版本,您现在可以将表达式传递给聚合:

 from django.db.models import F

 Task.objects.aggregate(total=Sum(F('progress') * F('estimated_days')))['total']

常量也可以,一切都可以组合:

 from django.db.models import Value

 Task.objects.aggregate(total=Sum('progress') / Value(10))['total']

关于python - Django 聚合 : Summation of Multiplication of two fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12165636/

相关文章:

sql - 获取最常用的多对多字段

python - 如何使用 Python 获得直方图中可变 bin 范围的相同 bin 宽度?

Django:在 "AppConfig.ready()"之后调用的信号/方法

Python readline() 和 Counter 在很长的行上导致 MemoryError

python - Django 在不同数据库中保存模型

python - 将额外参数传递给测试用例设置

python - 在 ManyToManyField 中定义最大关系

python - 调用异步任务 celery 时引发异常 : "NameError: global name * is not defined"

python - Tensorflow seq2seq 多维回归

python - Spyder 中的 "RuntimeError: asyncio.run() cannot be called from a running event loop"