Difference between _sql_constraints and _constrain

2020-05-27 17:58发布

问题:

I noticed there are 2 kinds of constraints on Odoo ERP. But I want to know what is the difference between _sql_constraints vs _constraints?

_sql_constraints = {
    ('email_uniq', 'unique(email)', ' Please enter Unique Email id.')
}

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

回答1:

_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")