1
votes

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

1
Adam the relation ship won't work like this, many2one is pointed to account.move and the one2many is in sale.order ?!! - Charif DZ
Yeah but it was a typing mistake... - Adam Strauss
BTW is it possible to create one2many field in sale.order without fkey? I am asking because without fkey how values relate to sale.order and sale.order without confirming or saving is not showing its id - Adam Strauss
So it's just for UI make it compute field with store=False I think It will not cause a problem on save because nothing will be saved in database, and try to make it many2many I think it's easier - Charif DZ
Finally many2many did my work :D - Adam Strauss

1 Answers

1
votes

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