Shravy
Shravy

Reputation: 666

How to add constraint for integer field in odoo?

In the created customized module, i have a many2one field named "BAND" and anothor field named "Amount" of type integer.I want to restrict the value of Amount field based on the employee BAND.For example if Employee BAND is C1 the amount should be less than 1000 and if Employee BAND is C2,then the amount should be less than 1500.

Upvotes: 2

Views: 2827

Answers (2)

Bhavesh Odedra
Bhavesh Odedra

Reputation: 11143

try with this:

_columns = {       
    'amount': fields.integer('Amount', size=64),
}

def _check_amount(self, cr, uid, ids, context=None):
    for employee in self.browse(cr, uid, ids, context=context):
        if employee.many2one_field and employee.many2one_field.name == 'C1':
            if employee.amount < 1000:
                return True
            else:
                return False
        elif employee.many2one_field and employee.many2one_field.name == 'C2':
            if employee.amount < 1500:
                return True
            else:
                return False
        #we may apply as many condition as you want
    return True    

_constraints = [
    (_check_amount, 'WARRING MESSAGE', ['amount', 'many2one_field'])
]

For Odoo documentation model constraints

Upvotes: 0

Thawatchai
Thawatchai

Reputation: 143

@api.constrains('BAND')
    def _check_BAND(self):
        if self.employee.band == 'C1':
             if self.amount > 1000:
                    raise ValidationError("the amount should be less than 1000")
        elif self.employee.band == 'C2':
             if self.amount > 1000:
                    raise ValidationError("the amount should be less than 1000")

Upvotes: 1

Related Questions