1

I am adding custom One2many field in sale.order form view just below the sale.order.line.

I am computing values on_change it is displaying values but when I am going to save the sales order it is generating error that

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)

Because I am creating one2many field before creating the order. But is there any way to get rid of this problem.

Edit: Error after replacing my code with Charif DZ code:

enter image description here

4

1 回答 1

1

永远不要在 onchange 事件中创建记录,它们会立即保存在数据库中,如果用户决定取消订单,而不是 create use 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
                  })

我希望这能帮助你好运

于 2020-01-10T06:18:35.753 回答