gpt4 book ai didi

python - 关系字段的 openerp sum 函数

转载 作者:太空狗 更新时间:2023-10-30 01:49:10 24 4
gpt4 key购买 nike

在 Openerp 中,我们有 object_A 和一个属于 object_B 的 one2many 字段。 Object_B 有一个浮点字段。在 object_A 中,我们有一个对应 object_B 的 one2many_list 小部件,因此我们自然会为每个新记录创建多行。
我知道这很简单,但我很难在 object_A 中编写一个函数来总结 Object_B 浮点列的总值。到目前为止我所拥有的是这样的:

def get_result(self, cr, uid, ids):
total = {}
for obj in self.browse(cr, uid, ids):
result=0.0
total[result]+= obj.o2m_field.float_field
return total

最佳答案

@DReispt 提供的代码应该可以工作,如果您批准一个答案,请批准他的答案,而不是我的。

要理解的重要一点是,OpenERP 中的函数字段返回一个字典,其中对象 ID 为键,给定对象的字段值作为关联值。

在您的原始代码中:

result = 0.0
total[result] += anything

会导致 KeyError,因为字典最初是空的(total = {} 在您的代码开头)。

DReispt 代码的较短版本是

def get_result(self, cr, uid, ids, context=None):
total = {}
for obj in self.browse(cr, uid, ids, context=context):
total[obj.id] = sum(o2m.float_field for o2m in obj.o2m_field)
return total

这个版本利用了 Python 的生成器表达式,它可以传递给 sum() 内置函数。它也稍微快一些,因为您避免了为每个对象多次访问 total 字典。

关于python - 关系字段的 openerp sum 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13981820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com