In Odoo 16 and onwards, the mechanism for adding records to One2many fields via code has indeed changed slightly. Instead of directly using `self.update()` to modify One2many fields, you can use the recordset methods like `create` or `write`.
Here's how you can add records to a One2many field in Odoo 16+:
# Assuming self is a record of the main model where line_ids is a One2many field
# Create a recordset for the related model 'comodel'
comodel_obj = self.env['comodel']
# Prepare the values to be added to the One2many field
values_to_add = {
'fieldname': something, # Replace 'fieldname' and something with your actual field and value
# Add other fields and values as needed
}
# Create a new record in 'comodel' and link it to the main record
new_record = comodel_obj.create(values_to_add)
# Add the newly created record to the One2many field 'line_ids'
self.write({
'line_ids': [(4, new_record.id)]
})
This snippet demonstrates how to create a new record in the related model ('comodel') and then link it to the main record by appending its ID to the One2many field 'line_ids' using the `(4, id)` syntax.
Ensure to replace `'fieldname'` and `something` with your actual field name and value that you want to set in the 'comodel'.
This should enable you to add records to the One2many field programmatically in Odoo 16 and newer versions.