How to Add Custom Sale Order Line in Odoo 12

There are two ways you can add custom sale order line in Odoo 12.

First Method

You can search the sale order first with the name or browse with the ID

sale_order = self.env['sale.order'].search([('name', '=', 'SO009')])

Now, you can see the sale order line IDs using the following:

sale_order.order_line

As this is a One2many relation, we need to use a tuple in the Odoo ORM write() method. Here is the list of data you can pass in a tuple to change data that has One2many or Many2many relation

Odoo ORM Documentation

You can now pass this as python dictionary for ‘order_line’ to sale.order of desired product as following:

sale_order_new.write({
'order_line': [
(0,0, {
'order_id': sale_order.id,
'product_id': 2003,
'price_unit': 3000.0,
'product_uom_qty': 2.0,
'name': ''
})
]
})

Second Method

In this method, you can simply define the order dictionary, and create a sale.order.line item with the order_id in reference. Here is an example

# define dictionary to add order_line
order_line_dict = { 'order_id' : 9, 'product_id': 2003, 'price_unit': 3000.0, 'product_uom_qty': 2.0, 'name': '' }

# search the order line for the sale order
sale_order_line = self.env['sale.order.line'].browse(9)

# create a new order line
sale_order_line.create(order_line_dict)

# print sale order lines
sale_order_line

Note

If you are doing/testing this on the Odoo Shell, then make sure to run the following after the changes to reflect on database:

self.env.cr.commit()

Odoo doesn’t call database cursor commit if you are coding on Odoo shell, it calls automatically though if you are doing it in a module. Just a friendly reminder!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.