Search code examples
odoo

How to add _sql_constraints to check char field lenght in odoo?


I have a fields.Char attribute “identification_id”, That field must have 11 characters. How can I add a _sql_constraints to check the length of that field and ensure it should be 11 ?


Solution

  • You can use the Check Constraints with length function

    _sql_constraints = {
        ('check_name', 'check(length(name)>10)', 'name must be at least 11 characters')
    }
    

    Edit:

    The constraint will not be added if you have already a record that did not satisfy it:

    ERROR demo odoo.sql_db: bad query: ALTER TABLE "hr_employee" ADD CONSTRAINT "hr_employee_check_name" check(length(name)>10)
    ERROR: ERROR:  The verification constraint "hr_employee_check_name" is broken by a line