Search code examples
pythonodooodoo-8

How to make constraint on a field


I want to perform a constraint on the jrestant that returns me the number of days between two dates which must also be positive.
How to make constraint on a field?

    def compa_date(self,cr,uid,ids,args,fields,context=None):   
        res = {}
        for self_brow in self.browse(cr,uid,ids,context):

            if self_brow.Date_ouv_pli or self_brow.date_depot:
                date_debut = datetime.strptime(self_brow.Date_ouv_pli,'%Y-%m-%d')
                date_fin = datetime.strptime(self_brow.date_depot,'%Y-%m-%d')
                res[self_brow.id] = (date_debut - date_fin).days                    
        return res

    _columns = {
        'date_depot' : fields.date('Date dépot de soumission'),
        'Date_ouv_pli' : fields.date('Date Ouverture Plis'),
        'jrestant': fields.function(compa_date,string='Jours restant')
    }

    def _check(self, cr, uid, ids, context=None):
        for product in self.read(cr, uid, ids, ['jrestant'], context=context):
            if jrestant < '0' :
                return False
        return True
    _constraints = [(_check, 'Days must be positive', ['jrestant'])]

Solution

  • Set store to True so the value of the functional field will be stored in the database, which allows you to set constraints on it.

    'jrestant': fields.function(compa_date, string='Jours restant', store=True)