Skip to Content
Menu
This question has been flagged
3 Replies
3850 Zobrazenia

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
Zrušiť
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
Zrušiť

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.

Autor

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
Zrušiť
Autor

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
Zrušiť
Related Posts Replies Zobrazenia Aktivita
0
máj 25
12
2
jan 25
2459
1
dec 24
6150
1
nov 24
2601
1
nov 24
1917