@api.onchange method on a one2many field doesn't save the changes
I am trying to update sibling records in an @api.onchange method to "de-activate" them when another sibling is "activated".
I am using the following code, but it doesn't update the relevant records:
class Child(models.Model):
_name = 'module_name.child'
parent_id = fields.Many2one('module_name.parent', string='My Parent')
partner_id = fields.Many2one('res.partner', string='My Partner', domain=[('customer', '=', True)])
is_active = fields.Boolean(string="Activated")
@api.onchange('is_active')
def _deactivate_siblings(self):
if self.is_active:
#the following line identifies siblings by parent id
siblings_and_me = self.search([('parent_id', '=', self.parent_id.id)])
#this line should update the siblings - but doesn't work
siblings_and_me.write({'is_active': False})
self.is_active = True
The code above does not "deactivate" the sibling records - So I end up with multiple active children. This should not happen.
I have also tried
self.search([('parent_id', '=', self.parent_id.id), ('id', '!=', self.id)]).write({{'is_active': False})
but this fails with a NewId error
Is there a different way to achieve this?
The parent Model is as follows:
class Parent(models.Model):
_name = 'module_name.parent'
child_ids = fields.One2many('module_name.child', 'parent_id', string="Children")
active_child_partner = fields.Many2one('res.partner', compute='_get_active_child_partner')
@api.depends('child_ids')
def _get_active_child_partner(self):
active_child = self.child_ids.filtered(lambda record: record.is_active == True)
return active_child['partner_id'] if len(active_child) == 1 else active_child[0]['partner_id']
Furthermore,
The form view for parent does not display the active child's partner.
My Template is as follows:
<record model="ir.ui.view" id="parent_form_view">
<field name="name">parent.form</field>
<field name="model">module_name.parent</field>
<field name="arch" type="xml">
<form string="Parent">
<sheet>
...
<field name="active_child_partner" />
<notebook>
<page>
<field name="child_ids" widget="one2many_list">
<tree string="Children" editable="bottom">
<field name="partner_id" options='{"always_reload": True}' domain=".." context="..."/>
<field name="other_field"/>
<field name="is_active"/>
</tree>
</field>
</page>
</notebook>
</sheet>
</form>
</field>
</record>
The field "active_child_partner" displays the label "Active child partner" but never has a partner populated there even though one child is active and has a partner.
How can I make sure that all siblings are updated (write should work in an onchange method)?
And how can I display the calculated partner?