This question has been flagged
6 Replies
11942 Views

I want to restrict the duplicate value in one2many field ,if it is there then it should not add in one2many field and it should raise error.

Avatar
Discard
Best Answer

Dear,

To check exist the same Product in the line level.

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class PurchaseOrder(models.Model):
_inherit = "purchase.order"

@api.multi
@api.constrains('order_line')
def _check_exist_product_in_line(self):
for purchase in self:
exist_product_list = []
for line in purchase.order_line:
if line.product_id.id in exist_product_list:
raise ValidationError(_('Product should be one per line.'))
exist_product_list.append(line.product_id.id)

Hope this code help you

Best Thanks,

Ankit H Gandhi.


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 !')]


Thanks

Avatar
Discard
Author

Thanks Niyas....But it is not working for me...i tried ..actually i added variants in new tab which has two field attribute and attribute values like product variants is there in product. In product variants is also adding duplicate attribute and as well as in sale order also ...other idea can u suggest me.

You can check the case in a new db, sql constrains will work with new database

Author

ok Niyas

Worked like charm ! Thanks Niyas.