在onchange中,当你想更新many2many的值时不要使用command list,使用RecordSet,我会稍微简化你的代码:
# don't use api.multi because it's by default multi with onchange, constraints, depends
@api.onchange('partner_id')
def find_projects(self):
# extract followers <RecordsSet>
projects_followers = self.env["mail.followers"].search([('partner_id', '=', self.partner_id.id), ('res_model', '=', 'project.project')])
# extract all project ids without duplication <list of int >
project_ids = projects_followers.mapped('res_id')
# no need to pass active = True Odoo by default add it
# search for porject <RecordSet>
projects = self.env["project.project"]search([('id', 'in', project_ids)])
# for debuging
self.debug_projects = len(projects_followers)
self.debug_projects2 = projects_followers
self.debug_projects3 = project_ids
# don't use any command by default Odoo detect witch project still in the field
# and witch one are added when you inspect write you will find that new ones are added
# by (4, id) the ones that were removed are (3, id)
self.project_ids = projects
编辑:
当我调查传递给 create 和 write 的字典值时,Odoo 正在将命令转换为仅update 命令,在我通过 ID 为 1,2 的 onchange 事件记录添加之后,字典中的命令是这样的!!:
'my_many2may' : [[1, 1, {u'name': u'1'}], [1, 2, {u'name': u'2'}]]
在新版本的 Odoo (> 11.0) 中,many2many 传递的命令是替换命令:[(6, 0, ids)] (bug was fixed):
要在您的情况下解决此问题,只需覆盖 create aand write 以修复您的字段的逗号:
def _fix_vals(self, vals):
""" fix bug of ignored record added by onchange event."""
commands = vals.get('project_ids', [])
if commands and not any(command[0] == 6 for command in commands):
vals['project_ids'] += [(4, command[1]) for command in commands if command[0] == 1]
@api.model
def create(self, vals):
self._fix_vals(vals)
return super(YourClassName, self).create(vals)
@api.multi
def write(self, vals):
self._fix_vals(vals)
return super(YourClassName, self).write(vals)
所以基本上当我像这样修复commands时:
[[1, 1, {u'name': u'1'}], [1, 2, {u'name': u'2'}]]
# to this
[(4,1), (4,2), [1, 1, {u'name': u'1'}], [1, 2, {u'name': u'2'}]]
注意:我注意到,当您手动添加记录时,通过了命令 (6,0, ids) 不会出现问题,这就是为什么我在修复它们之前检查了该命令是否存在