【问题标题】:How to use write() Method on a many2many field?如何在 many2many 字段上使用 write() 方法?
【发布时间】:2020-08-27 16:01:19
【问题描述】:

~...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)})

在上面的代码中,我试图做的是更新浏览模型(res)中的合作伙伴,但是名为 partner_id 的字段是一个 many2many 字段,我们可以在其中选择多个合作伙伴。

【问题讨论】:

  • 使用特殊的commands 格式来操作存储在字段中/与字段关联的记录集。这种格式是一个 list 三元组。如果您尝试从 onchange 方法更新它,请检查此 note
  • 我的onchange触发字段不是one2many或many2many字段,而是many2one字段,选择many2one字段后触发onchange方法,之后我需要更新many2many字段。
  • 为什么anc记录需要使用浏览?请添加Many2many字段的定义和test_record相关模型。
  • partner_id = fields.Many2many('res.partner', string="Specialist")
  • 尝试写入 Many2many 字段,如我的第一条评论中所示,res.write({'partner_id': [(4,self.partner_id.id)]})

标签: odoo odoo-12


【解决方案1】:

请注意,这仅适用于many2manyone2many,如下所示:

(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)
(6, 0, [IDs])          replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)

但在你的情况下,它可能是many2one,应该是

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

【讨论】:

  • 感谢回复,但是write方法中的字段不是many2one,在我的情况下是many2many。
猜你喜欢
  • 1970-01-01
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多