3a2*_*oub 4 python function openerp
在Openerp中,我们有object_A,其中一个one2many字段属于object_B.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
Run Code Online (Sandbox Code Playgroud)
@DReispt提供的代码应该有效,如果您批准答案,请批准他的,而不是我的.
需要了解的重要一点是,OpenERP中的函数字段返回一个字典,其中包含键的对象ID和给定对象的字段值作为关联值.
在您的原始代码中:
result = 0.0
total[result] += anything
Run Code Online (Sandbox Code Playgroud)
KeyError因为字典原来是空的(total = {}在你的代码的开头)会导致a .
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
Run Code Online (Sandbox Code Playgroud)
这个版本利用了Python的生成器表达式,可以传递给sum()内置函数.它也稍微快一些,因为您避免total为每个对象多次访问字典.
你需要循环o2m:
def get_result(self, cr, uid, ids, context=None):
total = {}
for obj in self.browse(cr, uid, ids, context=context):
total[obj.id] = 0
for o2m in obj.o2m_field:
total[obj.id] += o2m.float_field
return total
#example: {56: 12.34, 57: 56.78}
Run Code Online (Sandbox Code Playgroud)