Peewee 简明教程

Peewee - Constraints

约束是对字段中可以放入的可能值施加的限制。其中一个约束是主键。当在字段定义中指定 primary_key=True 时,每一行只能存储唯一的值 - 字段的同一值不能在另一行中重复出现。

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.

如果某个字段不是主键,仍然可以对其施加约束,以在表中存储 unique 值。字段构造器还具有约束参数。

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.

下面的示例在 age 字段上应用 CHECK 约束。

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'

这将生成以下数据定义语言 (DDL) 表达式 -

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)
);

因此,如果新行中 age<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

在字段定义中,我们还可以使用 DEFAULT 约束,如下面的 city 字段定义。

In the field definition, we can also use DEFAULT constraint as in following definition of city field.

city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])

因此,可以构建带有或不带有 city 明确值的对象模型。如果没有使用,city 字段将由默认值 - 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.