I'm trying to create a many2many field inside a Contact model that would have the same values like company_ids
inside a Users model at all times.
I was looking for the anwserws but the odoo docs have like two sentences about this topic and do not explain this firmly. Other sources seem to contradict themselfs because some says that related stored field do not update while other says that they do.
And after all I don't know the syntax for creating one myself because dosc are so poorly written.
I have this piece of code:
# -*- coding: utf-8 -*-
from odoo import models, fields, api
class custom_partner_fields(models.Model):
_inherit = 'res.partner'
company_ids = fields.Many2many(comodel_name='res.company', string='Related users Allowed companies', readonly=True)
It is creating field inside Contact model and now I need something to fill it in. Preferably without using onchange methods or automatic actions (I have automatic action right now - created via developer UI).
Just set the field in partner record after creating or editing the user record
__inherit = 'res.users'
@api.model
def create(self, vals):
res = super(TheClassName, self).create(vals)
res.partner_id.company_ids = res.company_ids
return res
@api.multi
def write(self, vals):
super(TheClassName, self).write(vals)
# if we edited company_ids we edit partners too
if 'company_ids' in vals:
# use mapped to call write one time good for performance
self.mapped('partner_id').write({'company_ids': vals['company_ids']})
return True
So when ever you edit company_ids
in user you do the same for related partner.
This will work for new user for sure but I think you need to handle existing users by a script or some solution to fill up the field.