Chapter 11: Constraints
The previous chapter introduced the ability to add some business logic to our model. We can now link buttons to business code, but how can we prevent users from entering incorrect data? For example, in our real estate module nothing prevents users from setting a negative expected price.
Odoo provides two ways to set up automatically verified invariants:
Python constraints and
SQL constraints are defined through the model attribute
_sql_constraints. This attribute is assigned a list of triples containing strings
(name, sql_definition, message), where
name is a valid SQL constraint name,
sql_definition is a table_constraint expression and
message is the error message.
You can find a simple example here.
Restart the server with the
-u estate option to see the result. Note that you might have data that prevents a SQL constraint from being set. An error message similar to the following might pop up:
For example, if some offers have a price of zero, then the constraint can’t be applied. You can delete the problematic data in order to apply the new constraints.
Reference: the documentation related to this topic can be found in
SQL constraints are an efficient way of ensuring data consistency. However it may be necessary to make more complex checks which require Python code. In this case we need a Python constraint.
A Python constraint is defined as a method decorated with
constrains() and is invoked on a recordset. The decorator specifies which fields are involved in the constraint. The constraint is automatically evaluated when any of these fields are modified . The method is expected to raise an exception if its invariant is not satisfied:
A simple example can be found here.
SQL constraints are usually more efficient than Python constraints. When performance matters, always prefer SQL over Python constraints.
Our real estate module is starting to look good. We added some business logic, and now we make sure the data is consistent. However, the user interface is still a bit rough. Let’s see how we can improve it in the next chapter.