Often, applications need to ensure data integrity, and enforce some validations to ensure that data is complete and correct.
The PostgreSQL database manager supports many useful validations, such as avoiding duplicates, or checking that values meet certain simple conditions. Model can declare and use PostgreSQL constraints for this.
Some checks require more sophisticated logic, and are better implemented as Python code. For these cases, we can use specific model methods implementing Python constraint logic.
SQL constraints are added to the database table definition and are enforced directly by PostgreSQL. They are defined using the _sql_constraints
class attribute.
It is a list of tuples, and each tuple has the format (name, code, error)
:
- name is the constraint identifier name
- code is the PostgreSQL syntax for the constraint
- error is the error message to present to users when the constraint is not verified
We will add two SQL constraints to the Book Model...