What is api.constrains

If you have a case when you need to validate some data before to be called create, write or unlink method you need to decorate the validation function with the api.constrains decorator. This decorator ensures that the function will be called before the mentioned methods. Also, this function should raise a validation error if the validation failed.

For Example, if we need to be sure that the field work_hours will not have smaller value than 10 we can create a validation function that will do that for us:

from openerp import models, fields, api

class PartnerContact(models.Model):
    _name = 'partner.contact'

    work_hours = fields.Float(string='Work Hours', index=True)

    @api.constrains('work_hours')
    def _validate_work_hours(self):
        if self.work_hours < 10:
            raise ValidationError("Field 'Work Hours' must be greater than 10")

1 Comments

Leave a Reply

Your email address will not be published.