- Peewee - Discussion
- Peewee - Useful Resources
- Peewee - Quick Guide
- Peewee - Using CockroachDB
- Peewee - PostgreSQL & MySQL Extensions
- Peewee - SQLite Extensions
- Peewee - Integration with Web Frameworks
- Peewee - Query Builder
- Peewee - Database Errors
- Peewee - Atomic Transactions
- Peewee - User defined Operators
- Peewee - Retrieving Row Tuples/Dictionaries
- Peewee - SQL Functions
- Peewee - Counting & Aggregation
- Peewee - Sorting
- Peewee - Subqueries
- Peewee - Relationships & Joins
- Peewee - Connection Management
- Peewee - Defining Database Dynamically
- Peewee - Using PostgreSQL
- Peewee - Using MySQL
- Peewee - Constraints
- Peewee - Create Index
- Peewee - Delete Records
- Peewee - Update Existing Records
- Peewee - Primary & Composite Keys
- Peewee - Filters
- Peewee - Select Records
- Peewee - Insert a New Record
- Peewee - Field Class
- Peewee - Model
- Peewee - Database Class
- Peewee - Overview
- Peewee - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Peewee - Constraints
Constraints are restrictions imposed on the possible values that can be put in a field. One such constraint is primary key. When primary_key=True is specified in Field definition, each row can only store unique value – same value of the field cannot be repeated in another row.
If a field is not a primary key, still it can be constrained to store unique values in table. Field constructor also has constraints parameter.
Following example apppes CHECK constraint on age field.
class MyUser (Model): name=TextField() city=TextField() age=IntegerField(constraints=[Check( name<10 )]) class Meta: database=db db_table= MyUser
This will generate following Data Definition Language (DDL) expression −
CREATE TABLE MyUser ( id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL, age INTEGER NOT NULL CHECK (name < 10) );
As a result, if a new row with age<10 will result in error.
MyUser.create(name="Rajesh", city="Mumbai",age=9) peewee.IntegrityError: CHECK constraint failed: MyUser
In the field definition, we can also use DEFAULT constraint as in following definition of city field.
city=TextField(constraints=[SQL("DEFAULT Mumbai ")])
So, the model object can be constructed with or without exppcit value of city. If not used, city field will be filled by default value – Mumbai.
Advertisements