Skip to Content
Menu
This question has been flagged
1 Reply
3841 Views

hi all iam a newbie to odoo , what iam trying to achieve is i want to prevent from adding duplicate products in order line , if the same exits already we should not able to add the duplicate product  , I tried like this but its not working 


@ api.constrains ('order_line') 

    def _check_exist_product_in_line (self): 

        product_ids = self.env ['product.product']. search ([('default_code', '=', 'KIB_PRF')]) 

        for line in self.order_line:

          # self.env ['sale.order.line']. create ({'product_id': product_id.id, 'order_id': self.id})

          if line.product_id in product_ids: 

            raise ValidationError (_ ('Product already added.'))

          # product_id.append (line.product_id.id)

Avatar
Discard
Best Answer

Hi,

Using the sql constrains, you can do this.


Take the case of sale order and sale order line, the field order_id in the sale order line is the Many2one field between these two model.


Suppose if you don't want to add duplicate products in order line, ie, apple(a product) can be selected once in a order line of a sale order, you can add the constrains like this,


_sql_constraints = [('order_product_uniq', 'unique (order_id,product_id)',     
'Duplicate products in order line not allowed !')]

See: How to Prevent selecting the same value in one2many field in odoo 10?


Thanks
Avatar
Discard
Author

hi niyas , thanks for the reply, but how to use this for my case whether i need to use this as a decorator for my function or inside the function . i dont understand could you please explain .

inherit the sale.order model and add the above lines, if you search _sql_constraints inside odoo code, you can see samples

Related Posts Replies Views Activity
3
Nov 23
15311
3
Nov 24
21078
1
Apr 23
4569
2
Dec 22
5497
1
Nov 22
2661