
- Peewee 教程
- Peewee - 主頁
- Peewee - 概述
- Peewee - 資料庫類
- Peewee - 模型
- Peewee - 欄位類
- Peewee - 插入新記錄
- Peewee - 選擇記錄
- Peewee - 篩選器
- Peewee - 主鍵 & 組合鍵
- Peewee - 更新現有記錄
- Peewee - 刪除記錄
- Peewee - 建立索引
- Peewee - 約束
- Peewee - 使用 MySQL
- Peewee - 使用 PostgreSQL
- Peewee - 動態定義資料庫
- Peewee - 連線管理
- Peewee - 關係 & 連線
- Peewee - 子查詢
- Peewee - 排序
- Peewee - 計數和聚合
- Peewee - SQL 函式
- Peewee - 檢索行元組/字典
- Peewee - 使用者定義運算元
- Peewee - 原子事務
- Peewee - 資料庫錯誤
- Peewee - 查詢生成器
- Peewee - 與 Web 框架的整合
- Peewee - SQLite 擴充套件
- Peewee - PostgreSQL 和 MySQL 擴充套件
- Peewee - 使用 CockroachDB
- Peewee 有用資源
- Peewee - 快速指南
- Peewee - 有用資源
- Peewee - 討論
Peewee - 約束
約束是對欄位中可輸入值的限制。其中一種此類約束是主鍵。當在欄位定義中指定 primary_key=True 時,每行只能儲存唯一值 - 同一欄位的相同值不能在另一行中重複。
如果一個欄位不是主鍵,仍然可以約束它以在表中儲存 unique 值。欄位建構函式也有約束引數。
以下示例對 age 欄位應用 CHECK 約束。
class MyUser (Model): name=TextField() city=TextField() age=IntegerField(constraints=[Check('name<10')]) class Meta: database=db db_table='MyUser'
這將生成以下資料定義語言 (DDL) 表示式 -
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 的新行將導致錯誤。
MyUser.create(name="Rajesh", city="Mumbai",age=9) peewee.IntegrityError: CHECK constraint failed: MyUser
在欄位定義中,我們還可以使用 DEFAULT 約束,如下面的 city 欄位定義所示。
city=TextField(constraints=[SQL("DEFAULT 'Mumbai'")])
因此,可以使用或不使用 city 的顯式值構造模型物件。如果不使用,city 欄位將填充預設值 - Mumbai。
廣告