【问题标题】:Odoo : How to clear a many2many field when a many2one field change?Odoo:当many2one字段发生变化时如何清除many2many字段?
【发布时间】:2022-04-24 13:29:56
【问题描述】:

我是 odoo 的新手。我使用 odoo 13,我有一个 many2one 字段和一个 many2many 字段,在 many2one 字段上有域。 我需要的是,如果用户更改了 many2one 字段,那么 many2many 会变空并准备好选择。 但我不知道如何在函数上编写代码,所以我尝试了一些变体,但它就是不来找我。 如果我使用它,当我第一次选择“industria”字段时会出现错误

class Partner(models.Model):
    _inherit = 'res.partner'
    industria = fields.Many2one('industria_model', string="Industria")
    marca = fields.Many2many('marca_model',
                             domain="[('industria_id', '=', industria)]", string="Marca")

    @api.onchange('industria')
    def get_price(self):
        self.marca = [(5)]
        # if self.marca:
        #     self.marca = [(5, 0, 0)]

【问题讨论】:

  • marca = False, marca = [(6, 0, [])], marca = [] 我想我记得所有这些都有效
  • 错误消息或回溯会很好;-)

标签: python python-3.x odoo odoo-13


【解决方案1】:

[(5)] 将被评估为 [5] 然后 Odoo 将尝试返回尚未创建的相应记录(第一次),您应该会看到以下错误:

Record does not exist or has been deleted. (Record: marca_model(5,), 

您可以简单地使用[(5,)] 清空marca 字段。

如果数据库中存在id为5的记录,你会得到与使用[(4, 5)]相同的结果

【讨论】:

    【解决方案2】:

    最后我用了这个

    @api.onchange('industria')
        def change_brand(self):
            self.marca = [(6, 0, [])]
    

    我已经测试过了,但是我必须重新启动 odoo 才能看到更改,只是更新模块不起作用

    【讨论】:

      【解决方案3】:

      您可以使用以下 3 种方式删除 many2many 的记录:

      @api.onchange('industria')
      def change_brand(self):
          for rec in self.marca:
              self.marca = [(3, rec.id, 0)] # only delete this record from m2m field
              # self.marca = [2,rec.id,0] 
              # self.marca = [5,0,0] 
      

      [(3, rec.id, 0)] 表示此记录仅从表单视图中删除,但在用户单击保存或创建按钮之前它位于相关表中,并且 [2,rec.id,0] 表示此从表和视图中删除记录,并且 [5,0,0] 从表和表单视图中删除所有 many2many 记录。 我使用了所有这些并且它们有效。 希望它有用:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多