如何保存 One2many 字段值?

How to save One2many fields values?

我正在 sale.order 表单视图中添加自定义 One2many 字段 sale.order.line.

我正在计算值 on_change 它正在显示值但是当我要保存销售订单时它生成错误

ValueError: Wrong value for tax.lines.order_id: sale.order(24,)

Python:

class SaleOrderInherit(models.Model):
_inherit = ['sale.order']

tax_line = fields.One2many('tax.lines', 'order_id', states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True, auto_join=True)

@on.change('partner_id')
def calculating_tax(self):
    //After some code
    self.env['tax.lines'].create({
              'tax_id': tax['tid'],
              'name': tax['name'],
              'amount': tax['tax'],
              'order_id': self.id
       })


class TaxLines(models.Model):
_name = 'tax.lines'

tax_id = fields.Char('Tax Id')
name = fields.Char('Tax Name')
amount = fields.Char('Tax Amount')
order_id = fields.Many2one('sale.order', string='Tax Report', ondelete='cascade', index=True, copy=False)

因为我在创建订单之前创建了 one2many 字段。 但是有什么办法可以解决这个问题吗

编辑: 用 Charif DZ 代码替换我的代码后出错:

切勿在 onchange 事件中创建记录,它们会立即保存在数据库中,如果用户决定取消订单而不是创建,则使用 new 和创建对象但不将其保存在数据库中怎么办。

       def calculating_tax(self):
              //After some code
              # to add record to your o2m use `|` oprator
              # if you want to clear record before start adding new records make sure to empty your field first by an empty record set like this 
              # self.tax_line = self.env['tax.lines']  do this before the for loop that is used to fill-up the field not put it inside or you will get only the last record 
              self.tax_line |=   self.env['tax.lines'].new({
                       'tax_id': tax['tid'],
                       'name': tax['name'],
                        'amount': tax['tax'],
                        # 'order_id': self.id remove the many2one because it's handled automaticly by the one2many
                  })

希望这对你有帮助,祝你好运