Django聚合:两个字段相乘的总和

2024-04-21Python开发问题
32

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

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11