I think I did this a thousand times, but today I am not able to achieve it and have a lot of doubts.
PURPOSE
I need to copy the records of an One2many field to my One2many field, but changing the value of a column. This action must be performed in an onchange method.
SCENARIO
I am in the model mrp.bom
. It has an One2many field named bom_line_ids
. It also has the Many2one field named product_id
.
Each time product_id
changes, I have to fill in automatically the bom_line_ids
of the current bill of materials record, taking the data from the bom_line_ids
field of other bill of materials. But these records will not be exactly the same, I need to modify a column.
EXAMPLE
In an onchange method, I need to copy the recordset mrp.bom.line(10, 11)
to my One2many field, but in my One2many field both records will have the field line_type
with the value 'standard'
(it does not matter the line_type
value of the source records).
MY ATTEMPT
I tried a lot of things. The closest attempt to the solution was this one. But this fails when the current bill of materials record has not been saved in the database yet, because of _origin
. The error says that bom_id
is NULL and it is mandatory... The problem is that if I do not write _origin
, that error raises always, it does not matter if the current bill of material already exists or not. And if I remove the bom_id
key from the default
dictionary, the new lines are added to the source One2many instead of mine...
@api.onchange('product_id')
def onchange_product_id(self):
if self.product_id and \
self.product_id.product_tmpl_id.bom_ids:
# Following lines are only for taking the source BoM
bom_ids = self.product_id.product_tmpl_id.bom_ids.filtered(
lambda r: not r.product_id)
bom_id = bom_ids[0] if bom_ids else False
# Following lines are for doing the copy
new_lines = self.env['mrp.bom.line']
for line in bom_id.bom_line_ids:
new_lines += line.copy(default={
'bom_id': self._origin.id,
'line_type': 'standard',
})
self.bom_line_ids = [(6, 0, new_lines.ids)]
CONCLUSION
I think I am making this complexer than it is, there must be some easier solution... Does anyone know how to do this?