odooodoo-13one2many

How to save One2many fields values?


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


Solution

  • Never create records in onchange events they are immidiatly saved in database what if the user decided to cancel the order, instead of create use new with create an object but doesn't save it in database.

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

    I hope this help you good luck