Search code examples
python-3.xfieldodooodoo-11

Odoo 11 : Problem while creating compute field in sale.order.line model


I want to put the bom_id of each products in sale.order.line model, to do that, I use computed field to get the bom id (mrp.bom). I need that for specified development where the goal is to show consummed materials according to company's calculation before going to prodction. Here is the code:

bom_id = fields.Integer(
    string='Bom ID',
    compute='_get_bom_id'
)

@api.multi
def _get_bom_id(self):
    bom_obj = self.env['mrp.bom']
    for record in self:
        bom_obj_id = bom_obj.search([('product_id', '=', record.product_id.id)])
        if bom_obj_id:
            record.bom_id = bom_obj_id.id
        else:
            record.bom_id = 0

The problem is that the field is not created in sale.order.line model, but if i remove the compute argument, it works. I already update the module, check in pgadmin, ... I know that the issue is related to the code but don't know where. Can you help me? Thank you


Solution

  • The type of the field you have created is wrong, it should be a Many2one instead of an Integer:

    bom_id = fields.Many2one(
        comodel_name='mrp.bom',
        string='Bom ID',
        compute='_get_bom_id'
    )
    

    You have also forgotten the api.depends decorator. In your case, the value should be recomputed each time the field product_id changes.

    In addition, a computed field always values False before executing its compute method, so if in your compute method the workflow does not give a value to the field, it still values False, which means that lines like record.bom_id = 0 or record.bom_id = False are useless.

    @api.multi
    @api.depends('product_id')
    def _get_bom_id(self):
        bom_obj = self.env['mrp.bom']
        for record in self:
            bom_obj_id = bom_obj.search([('product_id', '=', record.product_id.id)])
            if bom_obj_id:
                record.bom_id = bom_obj_id.id