It’s easy to add an SQL constraint to Odoo model - just use the
_sql_constraints list. Odoo Forms handle those constraints automatically. When you write your own controllers, you need to handle them by hand.
Let’s say with got this simple model:
When the constraint is violated, a
psycopg2.IntegrityError exception is thrown. You need to catch the exception and handle the problem. And here comes the tricky part - you will most likely encounter an
InternalError: current transaction is aborted, commands ignored until end of transaction block.
This happens because after an error PostgreSQL will not allow subsequent queries in the same transaction. You need to end the transaction first, by either committing or rolling back.
Here’s a full example: