Openerp sum function for relational fields

In Openerp, we have object_A with one single field belonging to object_B. Object_B has a float field. In object_A, we have one2many_list widget for the corresponding object_B, so naturally we will have several lines for each new record.
I know this is trivial, but it's hard for me to write a function to object_A to summarize the total value of the column float Object_B. That I still have something like this:

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 
+4
source share
3 answers

The code provided by @DReispt should work, and if you approve the answer, please confirm it, not mine.

It is important to understand that the function field in OpenERP returns a dictionary with the object identifiers for the key and the field value for the given object as the associated value.

In the source code:

 result = 0.0 total[result] += anything 

will cause a KeyError since the dictionary is empty first ( total = {} at the beginning of your code).

A shorter version of DReispt code will be

 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 

This version uses a Python generator expression that can be passed to the sum() built-in function. It is also slightly faster because you avoid accessing the total dictionary several times for each object.

+6
source

You need to loop 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} 
+5
source

Just for bumps, doing it in a functional way:

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

All Articles