Skip to Content
Menu
This question has been flagged
3 Replies
3834 Views

Hi,


When creating a new product, why the product name can be the same?

Is there a way to avoid this.  I don't want users to use the same product name during product creation.  


Thanks,
Wilson

Avatar
Discard
Best Answer

Kiran's suggestion is OK.
There is another possibility: The automated actions.
Here you have an example to prevent duplicated product names. You will find the complete intructions to set an automated action in the link I include below. 
The Model used for this action must be "product.template"

if record.name:
   existing_product = env['product.template'].search([('id','!=',record.id),('name','=',record.name)])
   if existing_product:
      raise UserError("You can't have the same Product Name in Odoo twice! (" + record.name + ")")

(Please look at https://odootricks.tips/automated-action-to-prevent-duplicates/  )

Hope this helps you. 

Avatar
Discard

Hello,
Just replace "raise Warning" by "raise UserError" and this is the best solution.

Thanks, Julien, you are right.
Raise UserError("xxx") applies since V14. Until V13 the sintax was raise Warning("xxx")
I'll change the answer with the new sintax.

Author

Thank You! It works like a charm.

Best Answer

Hi,

You can use SQL Constraints or Python Constraints to achieve this,

1. SQL Constraints

_sql_constraints = [
('name', 'unique (name)', 'The Product already Exists!'),
]

2. Python Constraints

@api.constrains('name')
def _check_name(self):
if self.name:
product_rec = self.env['product.template'].search(
[('name', '=', self.name), ('id', '!=', self.id)])
if product_rec:
raise UserError(_('Exists ! Already a product exists with same name'))

Eg: 


https://www.odoo.com/documentation/15.0/developer/howtos/rdtraining/11_constraints.html


Hope it helps,

Kiran K

Avatar
Discard
Author

I don't no idea how it works. Thanks anyway

Best Answer

Hello
I am running this code but I am getting the raise UserError message everytime a product is created having a unique or duplicate name. Could I be missing anything out?

if record.name:
existing_product = env['product.template'].search([('id','!=',record.id),('name','=',record.name)])
if existing_product:
raise UserError("You can't have the same Product Name in Odoo twice! (" + record.name + ")")

Is there something I am doing wrong. I go to your link and do the same code with default_code insted of name and that works fine.

Appreciate in advance

Update: I tried this code and it worked for me.


existing_product = env['product.template'].search([('name','=',record.name)])
if len(existing_product) > 1:
raise UserError("Product already in Odoo. (" + record.name + ")")

Avatar
Discard
Related Posts Replies Views Activity
0
May 25
12
2
Jan 25
2439
1
Dec 24
6146
1
Nov 24
2585
1
Nov 24
1913