Odoo Help


making field unique but not mandatory

shashank verma
on 6/15/13, 7:33 AM 1,482 views


i have a field "vat"

my requirement is to keep this field unique which accept either 9 or 10 digits only but this field should not be mandatory.

my following code-

def check_vat(eancode): # globally define function

if not eancode:
    return True
if len(str(eancode)) == 10:
    return True
if len(str(eancode)) == 9:
    return True

def _check_vat_key(self, cr, uid, ids, context=None):                      # function define within class
    for product1 in self.read(cr, uid, ids, ['vat11'], context=context):
        res = check_vat(product1['vat11'])
    return res

_constraints = [(_check_vat_key, 'You provided an invalid "VAT"..', ['vat11'])]

_columns = {
    'vat11': fields.integer('VAT', size=10),


_sql_constraints = [
    ('name_uniq77', 'unique(vat11)', 'VAT must be unique !'),]

so this code works f9 to accept only unique values.... but when i keep this "vat" field blank then it generate (_sql_constraint)validation error 'VAT must be unique. but i want this field not to be mandatory so what should i need to do to resolve this issue???

NOTE: iam using demo data



--Borni DHIFI --
| 6 8 9
Tunis, Tunisia
--Borni DHIFI --

Techno Functional Consultant Odoo(OpenERP) 


Skype : dhifi.borni

On 6/15/13, 8:34 AM


you problem in _sql_constraints with intger value (integer by default = 0) .so you can use _constraints :

for example :

def _check_unique_vat(self, cr, uid, ids, context=None):
        if not context:
            context = {}            
        product_ids = []        
        this = self.browse(cr, uid, ids[0]) 
        if  this.vat :
            product_ids = self.search(cr, uid, [ ('vat', '=', this.vat)])
        if len(product_ids) > 1:
                    return False
        return True

    _constraints = [(_check_unique_vat,("Vat   must be unique ."), ['vat'] ),
                   (_check_vat_key, 'You provided an invalid "VAT"..', ['vat'])

About This Community

This platform is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers.


Odoo Training Center

Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.

Test it now

Question tools

0 follower(s)


Asked: 6/15/13, 7:33 AM
Seen: 1482 times
Last updated: 3/16/15, 8:10 AM