Python Orm框架—Peewee

简介:这是一个轻量级orm框架

安装

  1. pip install peewee

连接数据库

peewee 目前仅支持三种关系型数据库: mysql , postgres 及 sqlite

一、连接Mysql

  1. from peewee import MySQLDatabase
  2. mysql_db = MySQLDatabase("database_name", host="localhost", port=3306, user="root", passwd="123123")
  3. mysql_db.connect()

二、连接postgres

三、 连接Sqlite

Model和Field

在ORM对象关系数据库中,Model是一个类,它对应的是数据库中的一张表,而Field是字段,它对应表中的字段,Model对象实例对应的是表中的某一条具体数据

Model类 -> 表

Field -> 表中的字段

Model对象实例 -> 表中具体一条数据

Model 类

  1. class BaseModel(Model):
  2. class Meta:
  3. database = db
  4. table_name = "user_info"

Field

字段类型及具体用法可以参考文档:https://www.osgeo.cn/peewee/peewee/models.html#field-types-table ,或者下表所示

字段类型 SQLite 波斯特雷斯尔 MySQL
AutoField 整数 序列号 整数
BigAutoField 整数 大系列 大整数
IntegerField 整数 整数 整数
BigIntegerField 整数 大整数 大整数
SmallIntegerField 整数 短整型 短整型
IdentityField 不支持 因特恒等式 不支持
FloatField 真实的 真实的 真实的
DoubleField 真实的 双精度 双精度
DecimalField 十进制的 数字的 数字的
CharField 瓦卡尔 瓦卡尔 瓦卡尔
FixedCharField 烧焦 烧焦 烧焦
TextField 文本 文本 文本
BlobField 斑点 二进制数据 斑点
BitField 整数 大整数 大整数
BigBitField 斑点 二进制数据 斑点
UUIDField 文本 UUID VARCHAR(40)
BinaryUUIDField 斑点 二进制数据 ValBoice(16)
DateTimeField 日期时间 时间戳 日期时间
DateField 日期 日期 日期
TimeField 时间 时间 时间
TimestampField 整数 整数 整数
IPField 整数 大整数 大整数
BooleanField 整数 布尔 布尔
BareField 非类型化的 不支持 不支持
ForeignKeyField 整数 整数 整数

所有字段类型接受的参数及其默认值:

  • null = False —允许空值
  • index = False —在此列上创建索引
  • unique = False —在此列上创建唯一索引。也见 adding composite indexes .
  • column_name = None —在数据库中显式指定列名。
  • default = None —任何值或可作为未初始化模型的默认值使用的调用
  • primary_key = False —表的主键
  • constraints = None - one or more constraints, e.g. [Check('price > 0')]
  • sequence = None —序列名(如果后端支持)
  • collation = None —用于排序字段/索引的排序规则
  • unindexed = False —指示应取消对虚拟表上的字段的索引(sqlite only*)
  • choices = None — optional iterable containing 2-tuples of value, display
  • help_text = None —表示此字段的任何有用文本的字符串
  • verbose_name = None —表示此字段的“用户友好”名称的字符串
  • index_type = None —指定自定义索引类型,例如,对于Postgres,可以指定 'BRIN' 或 'GIN' 索引。
  1. class Person(BaseModel):
  2. name = CharField(max_length='16')
  3. age = IntegerField()
  4. height = IntegerField()
  5. sex = BooleanField(default="male")