美文网首页
python pony 常用操作

python pony 常用操作

作者: 愤愤的有痣青年 | 来源:发表于2022-10-18 15:46 被阅读0次

    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

    2.2 外键

    2.3 主键

    2.4 联合主键

    2.5 非空

    2.6 唯一

    2.7 字段备注

    2.8 字段默认值

    3. 查询

    3.1 查询所有

    3.2 等于 大于 小于 查询

    3.3 in 查询

    3.4 like 查询

    3.5 多表连接查询

    3.6 子查询

    3.7 聚合查询(sum count, distinct)

    3.8 or and

    4. 修改

    5. 删除

    6. 创建

    在创建完表结构后,可以使用db.generate_mapping(create_tables=True)来创建表

    相关文章

      网友评论

          本文标题:python pony 常用操作

          本文链接:https://www.haomeiwen.com/subject/dnwoartx.html