Help

0

Odoo 12: Passing parameter to compute method on a compute field

Avatar
cabrejua

Hello mates!

I've got a question related to computed fields on Odoo 12.

My code is something like this:

compute_blue_field1 = fields.Float('Value for BLUE', compute='_compute_method_1')

compute_red_field2 = fields.Float('Value for RED', compute='_compute_method_2')

...

def _compute_method_2(self):
    list = self.env['other.model'].search([('product_id', '=, self.id),('color', '=', 'blue')]).mapped('other_id')

    self.compute_field1 =calculate_avg(list)

def _compute_method_2(self):
    list = self.env['other.model'].search([('product_id', '=, self.id),('color', '=', 'red')]).mapped('other_id')

    self.compute_field1 =calculate_avg(list)


The compute method is almost the same, only differs in the bold part, which is a selection of colors ('color', '=', whathever color in the selection field)

So, is there any other way to pass the parameter 'red', 'blue' on the compute field in order to simplify my code? Because i have to do the same for a bunch of different colors. Something like this (but it is not possible):

compute_blue_field1 = fields.Float('Value for BLUE', compute='_compute_method('blue')')

compute_red_field2 = fields.Float('Value for RED', compute='_compute_method('red')')

def _compute_method_2(self, color):

Thank you

Avatar
Discard
2 Answers
1
Avatar
Odoo Tools
Best Answer

You can use lambda for that case:

    def _compute_color(self, color):
        for record in self:
            if color == "blue":
                record.compute_blue_field = color # for simplicity color is considered as final val
            if color == "red":
                record.compute_red_field = color

    compute_blue_field = fields.Char(compute=lambda self: self._compute_color("blue"))
    compute_red_field = fields.Char(compute=lambda self: self._compute_color("red"))

Simultaneously, it is not a very good approach, especially since the compute method would be triggered for each field individually.

In this simple case it is easier to rely upon the field label.

colors = ["blue", "red"]

    def _compute_color(self):
        for record in self:
            for color in colors:
                field_key = "compute_{}_field".format(color)
                record[field_key] = color # for simplicity color is considered as final val

    compute_blue_field = fields.Char(compute=_compute_color)
    compute_red_field = fields.Char(compute=_compute_color)
Avatar
Discard
0
Avatar
cabrejua
Best Answer

Thanks @Odoo Tools! That's a very good approach :)

1 Comment
Avatar
Discard
Avatar
Odoo Tools
-

Please accept the answer then