模型(Model)类包含一个或多个属性,这些属性是 Peewee 中 Field 类的对象。Base Field 类不是直接实例化的。Peewee 为等效的 SQL 数据类型定义了不同的子类。
Field 类的构造函数具有以下参数
Sr.No | Constructor & Description |
---|---|
1 | column_name (str) Specify column name for field. |
2 |
primary_key (bool) |
3 |
constraints (list) |
4 |
choices (list) |
5 |
null (bool) |
6 |
index (bool) |
7 |
unique (bool) |
8 |
Default |
9 |
collation (str) |
10 |
help_text (str) |
11 |
verbose_name (str) |
Field类的子类映射到各种数据库中对应的数据类型,比如SQLite、PostgreSQL、MySQL等。
数字字段(Numeric Field)类
Peewee 中的数字字段类如下所示:
Sr.No | Field classes & Description |
---|---|
1 | IntegerField Field class for storing integers. |
2 |
BigIntegerField |
3 |
SmallIntegerField |
4 |
FloatField |
5 |
DoubleField |
6 |
DecimalField
|
文本字段(Text fields)
Peewee 中可用的文本字段如下:
Sr.No | Fields & Description |
---|---|
1 | CharField Field class for storing strings. Max 255 characters. Equivalent SQL data type is varchar. |
2 |
FixedCharField |
3 |
TextField |
二进制字段
Peewee 中的二进制字段描述如下:
Sr.No | Fields & Description |
---|---|
1 | BlobField Field class for storing binary data. |
2 |
BitField |
3 |
BigBitField |
4 |
UUIDField |
日期和时间字段
Peewee 中的日期和时间字段如下 –
Sr.No | Fields & Description |
---|---|
1 | DateTimeField Field class for storing datetime.datetime objects. Accepts a special parameter string formats, with which the datetime can be encoded. |
2 |
DateField |
3 |
TimeField |
由于 SQLite 没有 DateTime 数据类型,因此该字段被映射为字符串。
外键字段(ForeignKeyField )
此类用于在两个模型中建立外键关系,从而建立数据库相应的表。此类使用以下参数实例化 :
Sr.No | Fields & Description |
---|---|
1 | model (Model) Model to reference. If set to ‘self’, it is a self-referential foreign key. |
2 |
field (Field) |
3 |
backref (str) |
4 |
on_delete (str) |
5 |
on_update (str) |
6 |
lazy_load (bool) |
外键字段示例
from peewee import *
db = SqliteDatabase('mydatabase.db')
class Customer(Model):
id=IntegerField(primary_key=True)
name = TextField()
address = TextField()
phone = IntegerField()
class Meta:
database=db
db_table='Customers'
class Invoice(Model):
id=IntegerField(primary_key=True)
invno=IntegerField()
amount=IntegerField()
custid=ForeignKeyField(Customer, backref='Invoices')
class Meta:
database=db
db_table='Invoices'
db.create_tables([Customer, Invoice])
执行上述脚本时,将运行以下 SQL 语句查询 –
CREATE TABLE Customers (
id INTEGER NOT NULL
PRIMARY KEY,
name TEXT NOT NULL,
address TEXT NOT NULL,
phone INTEGER NOT NULL
);
CREATE TABLE Invoices (
id INTEGER NOT NULL
PRIMARY KEY,
invno INTEGER NOT NULL,
amount INTEGER NOT NULL,
custid_id INTEGER NOT NULL,
FOREIGN KEY (
custid_id
)
REFERENCES Customers (id)
);
SQLiteStudio GUI 工具中验证, 表结构如下:
其他字段类型
Peewee 中的其他字段类型包括 –
Sr.No | Fields & Description |
---|---|
1 | IPField Field class for storing IPv4 addresses efficiently (as integers). |
2 |
BooleanField |
3 |
AutoField |
4 |
IdentityField |
酷客网相关文章:
评论前必须登录!
注册