Difference between _sql_constraints and _constraints on OpenERP/Odoo?

百般思念 提交于 2019-12-03 03:37:16
Bhavesh Odedra

_sql_constraints means it will set constraint on postgresql database side.

_sql_constraints = [
     ('email_uniq', 'unique(email)', ' Please enter Unique Email id.'),
     ]

Where:

  • email_uniq means constraint name,

  • unique(email) means unique is name of constraint. email is a field name which constraint will apply on that field.

  • 'Please enter Unique Email id.' is a message and it will display on pop-up window when constraint would be violated.

_constraints is python constraint. We can give our logic to set constraints. For example:

_constraints = [
     (_check_qty_and_unitprice, u'Qty must be more than 0', ['product_qty', 'cost_unit']),
     ]

Where :

  • _check_qty_and_unitprice is a function name where we need to apply our logic.

  • 'Qty must be more than 0' is a message and it will display on pop-up window when constraint would be violated (the python function returns False).

  • ['product_qty', 'cost_unit'] is a list of field name which means constraint will fire for these two fields.

As of the new Odoo API python constraint have a new and simpler decorator. The below example can be written like this:

from openerp.exceptions import ValidationError

@api.constraints('product_qty', 'cost_unit')
def _check_something(self):
    for record in self:
        if record.product_qty < 1:
            raise ValidationError("Qty must be more than 0")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!