Django聚合:两个字段的乘法求和 [英] Django Aggregation: Summation of Multiplication of two fields

查看:2846
本文介绍了Django聚合:两个字段的乘法求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些模型这样的东西

I have a model some thing like this

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

现在我想做在数据库级别计算 Sum(progress * estimated_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聚合:两个字段的乘法求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆