当前位置:   article > 正文

21python框架之peewee_python peewee

python peewee

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

1、通过pip安装peewee

pip install peewee
  • 1

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

python -m pwiz -e mysql -H localhost -p 3306 -u root -P  -t tb_address,bt_user vo_erp > models.py
  • 1
  • -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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/172775
推荐阅读
相关标签
  

闽ICP备14008679号