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 applies 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 explicit value of city. If not used, city field will be filled by default value – Mumbai.

Advertisements