Search code examples
odooodoo-12

How to use write() Method on a many2many field?


~...py

@api.onchange('test_record')
def abcde(self):
    rec = self.test_record.id
    res = self.env['anc'].browse(rec)
    res.write({'partner_id': (4,self.partner_id.id)})

On the above code what im trying to do is updating a partner in the browsed model(res),But the field named partner_id is a many2many field,where we can select multiple partners.


Solution

  • please note this is only for many2many or one2many as following:

    (0, 0,  { values })    link to a new record that needs to be created with the given values dictionary
    (1, ID, { values })    update the linked record with id = ID (write *values* on it)
    (2, ID)                remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
    (3, ID)                cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
    (4, ID)                link to existing record with id = ID (adds a relationship)
    (5,)                    unlink all (like using (3,ID) for all linked records). Needs to be a tuple, thus the comma.
    (6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
    

    but in your case it is probably many2one which should be as

    def abcde(self):
        rec = self.test_record.id
        res = self.env['anc'].browse(rec)
        res.write({'partner_id':[(4,self.partner_id.id)]}) # you need to add it as list
    
    

    starting from Odoo 16.0 you could use Command. more details:

    Command.create({ values })
    Command.update(id, { values })
    Command.delete(id)
    Command.unlink(id)
    Command.link(id)
    Command.clear()
    Command.set(id)
    

    an example of using them would be:

    from odoo import Command
    
    
    invoice_line_ids = [
        Command.create({'product_id': 200, 'quantity': 5}),
        Command.create({'product_id': 300, 'quantity': 5}),
    ]
    
    # Combining update & create
    line_ids = [
        Command.update(line_ids[0].id, {'balance': 300}),
        Command.update(line_ids[1].id, {'credit': 200}),
        Command.create({
            'balance': -100,
            'account_id': 4,
        })
    ]
    
    
    move_finished_ids = [
        Command.delete(move.id) for move in production.move_finished_ids if move.bom_line_id
    ]
    
    user_ids = [
        Command.unlink(user.id) for user in removed_users if user.is_doctor
    ]
    
    user_ids = [Command.link(user.id) for user in allowed_users]
    
    user_ids = [Command.clear()]
    
    user_ids = [Command.set(allowed_users.ids)]