Search code examples
odoo-8odooodoo-9

sql_cosntraints on exitsing field from original module


In product.template there is field default_code. Is it' possible to add sql_constraints that default code should be unique. Because this code doesn't work. Or do i need override default_code field in my costume module?

class ProductProduct(models.Model):
    _inherit = 'product.template'


 _sql_constraints = [
    ('code_uniq', 'unique (default_code)', "Default code already exists!"),
]

Solution

  • I would add the constraint on model product.product because that's where this information (product reference) really is used. But default_code on product.template will only work since Odoo V10. In Odoo V8 and V9 it was a unstored related field, so not in DB. So you have to add the constraint on model product.product.

    class ProductProduct(models.Model):
        _inherit = 'product.product'
    
        _sql_constraints = [
            ('code_uniq', 'unique(default_code)', "Default code already exists!"),
        ]
    

    Important to know: If the module, which sets up the constraint, is updated while the constraint will fail (e. g. the default_code actually twice in db), it won't create a sql constraint in db. So you have to clean up the data and update the module again or create the constraint in the db by yourself.