Search code examples
odooodoo-10

search products in multicompany mode Odoo


Impacted versions: Odoo 10 CE with multi company

Description : I'm trying to add random alphanumeric value to default_code of products
it works fine in a single company Odoo but not in a multi-company instance

here's my functions that i'm calling in a cron who run every night

@api.multi
def affect_sku(self):
    _logger.info("running affect_sku")
    Product = self.env['product.product']
    _logger.info("Model ::: %s" % Product)
    product_ids = Product.search([('active', '=', True), ('default_code', '=', '')])
    _logger.info("Les Produits ::: %s " % product_ids)
    if product_ids:
        for product_id in product_ids:
            _logger.info("Product id : %s" % product_id)
            product = Product.browse(product_id.id)
            _logger.info("Old Product default code : %s" % product.default_code)
            x = self.randomStringDigits(13)
            y = self.env['product.product'].search([('active', '=', True), ('default_code', '=', x)])
            _logger.info("y = %s" % y)
            while y :
                x = self.randomStringDigits(13)
                y = self.env['product.product'].search([('active', '=', True), ('default_code', '=', x)])
            product.default_code = x
            _logger.info("SKU de %s : %s" % (product.id, product.default_code))

Solution

  • Use SUPER USER because he have the privilege to see all product, and you can enhance your code a little bit:

    # and use model for crons
    @api.model
    def affect_sku(self):
        _logger.info("running affect_sku")
        Product = self.env['product.product'].sudo() # use SUPER USER Jus to skip any access rights
        _logger.info("Model ::: %s" % Product)
        # no need to pass active it's passed by default
        product_ids = Product.search(['|', ('default_code', '=', ''), ('default_code', '=', False)])
        _logger.info("Les Produits ::: %s " % product_ids)
        # no need to check just loop directly
        for product in product_ids:
                _logger.info("Product id : %s" % product)
                # no need to browse it's all ready a record set
                _logger.info("Old Product default code : %s" % product.default_code)
                while True :
                    random_code = self.randomStringDigits(13)
                    # no need to pass active and use search_count
                    if not self.env['product.product'].search_count([('default_code', '=', random_code )]):
                        break
                product.default_code = random_code
                _logger.info("SKU de %s : %s" % (product.id, product.default_code))