如何为OpenERP模型声明_constraints?

时间:2014-11-11 10:35:16

标签: constraints openerp openerp-7

我创建了一个新模型:

class rpe_mandate(orm.Model):
    _name = 'rpe.mandate'

    def _check_dates(self, cr, uid, ids, context=None):
        for rec in self.browse(cr, uid, ids):
            delivery_date = rec.delivery_date
            receipt_date = rec.receipt_date
            if delivery_date > receipt_date:
                return False
        return True

    _columns = {
        'delivery_date': fields.date('Delivery date'),
        'receipt_date': fields.date('Receipt date'),
    }

    _constraints = [
        (_check_dates, 'Error! Delivery date must be earlier than receipt date.', ['delivery_date', 'receipt_date',])
    ]

如果收货日期早于交货日期,我想要显示错误消息。

但是对于我的代码,在我保存记录时没有发生任何事情,在这两种情况下(如果收货日期早于交货日期,反之亦然 - 我也试过检查我是否做过错了 - )

2 个答案:

答案 0 :(得分:0)

试试此代码

def _check_dates(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids):
        delivery_date = rec.delivery_date
        receipt_date = rec.receipt_date
        if delivery_date > receipt_date:
            raise osv.except_osv(_("Alert !!"),_("Delivery date must be earlier than receipt date"))
    return True

别忘了导入

来自openerp.tools.translate import _

答案 1 :(得分:0)

您正在为rpe_mandate生成新记录,但是通过many2many字段。因此,当您在弹出窗口中单击“保存”时,它不会存储在数据库中。您必须单击“保存”按钮,但在主窗体中,才能看到错误消息。