This question has been flagged
7 Replies
4881 Views

I am populating EAN13 codes in a method and assigning them to a product_product item.

However, I would like to test in advance if value already exists for any other product.

How is tested in Odoo if there is any product_product with a given EAN13 value?

Or, as a more general question, how do you check in Odoo if there is any product with a certain value (say FOOBAR) in a given field? 

Avatar
Discard
Best Answer

You need to do a search on the model. Take an example

def check_ean13(self, cr, uid, ean13, context=None):
    prod_count = self.pool.get('product.product').search(cr, uid, [('ean13','=', eanval)], count=True)
    if prod_count > 0:
#product with the field ean13 and eanval exist
else:
#there is no product with that ean13 value
Avatar
Discard
Author

But if I try that within a create method, 'cr' and 'uid' are not defined, right? Are they needed for the search method?

That depends on what api style you are using my example was using old api that still works. But the same apply without cr and uid for the new api

Author

Thanks Axel, a nice chap posted this url https://www.odoo.com/documentation/8.0/reference/orm.html#porting-from-the-old-api-to-the-new-api for other question I made. That url helps to understand both APIs, strongly recommended for those of us who are struggling to understand the basics in Odoo.

Best Answer

Hello,

You can also apply unique constraint for ean13, in case if you don't want generate duplicate ean13.

You can define unique constraint as below:

_sql_constraints = [

('ean_13_unique', 'unique (ean13)', 'The EAN13 code must be unique!')

]

Or if you want to use python method, check it as below:

@api.multi

def check_ean13(self, ean13):

    for rec in self:

        prod_recs = self.search([('ean13', '=', rec.ean13), ('id', '=', rec.id)], count=True)

        if prod_recs > 0:

            #process if duplicate ean13 exists for another product

        else:

            #process if ean13 is unique.

Hope this helps!

Thanks,

Kalpana Hemnani

Avatar
Discard
Author

Thanks for the side note Kalpana. This is helpful information and I am sure it will be useful in the future, in this specific case I don't want to enforce it across all code, just in one method. Now I am wondering how to retrieve ean13 code given a product.product ID. I am sure is easy once you know where to look for it.

Author Best Answer

As additional comment to this post, ean13 is part of product.product but it is populated in product.template. This is weird (IMHO) and there is even a note in the source code stating that ean13 population should be moved into product.product.

So if you are modifying create method it is normal that ean13 is not present in product.product create, as it is handled by product.template create.

Avatar
Discard