21python框架之peewee

一、安装peewee模块及通过已有表导出,自动生成model

1、通过pip安装peewee

pip install peewee

2、导出表结构,自动生成model

python -m pwiz -e mysql -H localhost -p 3306 -u root -P  -t tb_address,bt_user vo_erp > models.py
  • -e mysql:连接的是mysql库
  • -H :数据库主机
  • -p:数据库端口
  • -u:数据库用户名
  • -P:密码
  • -t:(tb_address,bt_user)表名称,多个时以逗号分隔
  • vo_erp:数据库名称
  • models.py:生成的文件

二、定义数据库连接和model

1、class Meta:

  • database:连接数据库
  • table_name:该mudel对应的数据表

2、常用字段类型

  • IntegerField
  • CharField
  • TextField
  • DateTimeField
  • ForeignKeyField:from_user = ForeignKeyField(关联的Model, backref=“外键名称”,相当于所关联的Model多了此属性)

3、字段属性

  • null = False – 非空约束
  • index = False – 此字段建立索引
  • unique = False – 唯一约束
  • column_name = None – Model对应的数据库字段名称
  • default = None – 设置默认值
  • primary_key = False – 主键约束
  • constraints = None - 检查约束e.g. [Check(‘price > 0’)]
  • sequence = None – sequence name (if backend supports it)
  • collation = None – collation to use for ordering the field / index
  • unindexed = False – indicate field on virtual table should be unindexed (SQLite-only)
  • choices = None – optional iterable containing 2-tuples of value, display
  • help_text = None – string representing any helpful text for this field
  • verbose_name = None – string representing the “user-friendly” name of this field
  • index_type = None – specify a custom index-type, e.g. for Postgres you might specify a ‘BRIN’ or ‘GIN’ index.
db=MySQLDatabase("vo_erp_test",host="localhost",port=3306,user="root",password="123456")
class BaseModel(Model):
    class Meta:
        database=db
class Person(BaseModel):
    id=IntegerField(primary_key=True)
    first_name=CharField()
    last_name=CharField()
    age=IntegerField()
    class Meta:
        table_name="bt_person_info"
        database=db

class Pet(BaseModel):
    id=IntegerField(primary_key=True)
    type=CharField()
    name=CharField()
    # master_id=ForeignKeyField(Person,related_name="pet_master")
    master_id=IntegerField()

    class Meta:
        table_name="bt_pet_info"

class Address(BaseModel):
    id=IntegerField(primary_key=True)
    type
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值