Search code examples
odooodoo-8openerp-8

Please correct me on the following code in Odoo


This is the following code in Odoo and does not work as I expected.

 def _check_dates(self, cr, uid, ids, context=None):    
    for rec in self.browse(cr, uid, ids, context=context):
        if rec.rdate and rec.gdate :
        start = date.strftime(str(rec.rdate), "%Y-%m-%d")
        end = date.strftime(str(rec.gdate), "%Y-%m-%d")
        if start >= end:
                return False
    return True

    _constraints = [
        (_check_dates, 'Error ! Received Date must be less or equal than given Date', ['rdate'])
        ]

Please correct me anyone. Thanks


Solution

  • Using the new Odoo 8 ORM API (no need to add anything to the _constraints list, which is now deprecated):

    @api.one
    @api.constrains('rdate', 'gdate')
    def _check_dates(self):
        if self.rdate and self.gdate:
            start = fields.Date.from_string(self.rdate)
            end = fields.Date.from_string(self.gdate)
            if start > end:
                raise exceptions.ValidationError("Error! Received Date must be less or equal than given Date")
    

    Note: I changed start >= end to start > end to make it consistent with your error message (since the previous code didn't accept equal dates).


    Alternatively you can set it up as an SQL constraint, which has the benefit of working on a deeper, database level:

    _sql_constraints = [
        (
            'rdate_gdate_check',
            'check(rdate <= gdate)',
            "Error! Received Date must be less or equal than given Date",
        ),
    ]