跳至內容
選單
此問題已被標幟

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

頭像
捨棄
最佳答案

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)
頭像
捨棄
作者 最佳答案

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

頭像
捨棄

Please accept the answer then

相關帖文 回覆 瀏覽次數 活動
2
2月 23
3778
2
7月 21
12110
2
3月 21
8911
1
11月 19
11847