Leon Nguyen
Leon Nguyen

Reputation: 197

How to sum all values of all records of a field? (Odoo 13)

Suppose I have two float fields:

num = fields.Float('Number')
sum_num = fields.Float('Sum all values of the num field')

I created the first records and put value: 1.0 in the num field ;

num = 1.0

and want the result in the sum_num field is 1.0 ;

sum_num = 1.0

Then I created the second record and put value: 2.0 in the num field ;

num = 2.0

and want the result in the sum_num field is 3.0 ;

sum_num = 3.0

and so on...

I'd tried to used compute field like this:

 sum_num = fields.Float(compute='_sum_num', string='Sum all values of all records of the num field')

 @api.depends('num')
 def _sum_num(self):
 for rec in self:
   if rec.num:
      rec.sum_num += rec.sum

But I got the error with this way!

So how do sum all values of all records of the num field?

Please help!

Thank you!

Upvotes: 3

Views: 2196

Answers (1)

jo541
jo541

Reputation: 1155

I don't be sure the utility of your code but is it possible.

First in v13 the compute method must all the time set a value in field. Because in v13 Odoo doesn't set a default value in your compute.

Second. You should iter on each record and set the sum of records.

num = fields.Float('Number')
sum_num = fields.Float(compute='_sum_num', string='Sum all values of all records of the num field')

 @api.depends('num')
 def _sum_num(self):
     # fetch all records for your model and sum num field value
     records_sum = sum(self.env["your.model"].search([]).mapped('num'))
     # Iter on each records to set records_sum
     for rec in self:
         rec.sum_num = records_sum

Upvotes: 3

Related Questions