Tuesday 10 July 2012

_constraints in Openerp

_constraints

    _constraint is a predefine field in OpenERP. It is used for adding a constraint on the object. It takes list of touple as its argument.The touple inside the list contains three parameter

1. Method(to check the constraint)
2. The Message(Constraint for End User)
3. List of Fields(fields to apply the constraint)
   
    _constraint will fire if the condition returns False on creation and updation of the record and display the message.

    The example code for the _constraint is displayed bellow.
   

 def _check_length(self, cr, uid, ids, context=None):
    record = self.browse(cr, uid, ids, context=context)
    for data in record:
        if data.length < 0:
            return False
    return True

 _columns = {
        'length': fields.integer('Length'),
    }

 _constraints = [(_check_length, 'Error: Length must be Positive', ['length'])]



    In the folloeing example the constraint is set on length field, when the record saved in the database it will check if the length is positive or negative, if it 's negative the constraint gets fired and the message will be display to end user.

No comments:

Post a Comment