This question has been flagged
1 Reply
4235 Views

hello

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

Avatar
Discard
Best Answer

Hi,

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'])
                  ]
Avatar
Discard