from pony import orm
1. 连接
创建数据库连接对象, 此时并未连接数据库,后续可以使用该对象来设计表结构,若需要查询,则必须在连接完数据表之后
db = orm.Database()
声明数据库绑定信息,更多数据库的绑定方式参考文档
https://docs.ponyorm.org/firststeps.html#database-binding
db.bind(provider='sqlite', filename='database.sqlite', create_db=True)
2. 表设计
表的类需要继承db.Entity
类
class Person(db.Entity):
_table_ ='persion'
id = PrimaryKey(int, auto=True)
name = orm.Required(str)
age = orm.Required(int)
2.1 字段声明
字段使用如下方式声明
-
orm.Required
必须的 -
orm.Optional
可选的 -
orm.PrimaryKey
主键 -
orm.Set
声明被属于,用在外键处
字段有如下属性: -
py_type
类型,具体的见2.2章节 -
nullable
是否为空,当为True
时,等效于orm.Optional
-
unique
是否是唯一 -
column
字段名称,若为空,则使用变量名来命名字段 -
auto
是否自增 -
default
默认值 -
index
普通索引 -
py_check
指定一个对该字段的检查函数,函数接收参数数据,返回一个布尔值,例如gpa = Required(float, py_check=lambda val: val >= 0 and val <= 5)
-
cascade_delete
是否支持级联删除 -
size
整数字段的位数,只允许为 8 16 24 32 64
attr1 = Required(int, size=8) # 8 bit - TINYINT in MySQL
attr2 = Required(int, size=16) # 16 bit - SMALLINT in MySQL
attr3 = Required(int, size=24) # 24 bit - MEDIUMINT in MySQL
attr4 = Required(int, size=32) # 32 bit - INTEGER in MySQL
attr5 = Required(int, size=64) # 64 bit - BIGINT in MySQL
-
max_len
字符串的最大长度 -
max
/min
指定数字的最大/最小值
2.2 字段格式
- str 字符串
- int 整数
- float 浮点数
- datetime 日期
- time 时间戳
- bool 布尔值
- Json
网友评论