当前位置:   article > 正文

Peewee基本使用_peewee in

peewee in
  • Peewee 即 Python OMR 框架之一。

peewee安装&配置

通过 pip instll peewee
新建 models.py 模型文件
在 models.py 中加入以下基础代码
运行 models.py,在 mysql 中生成 new_record 表
  • 1
  • 2
  • 3
  • 4

peewee使用

from peewee import *
from settings import DATABASES

//  连接数据库
MYSQL_DB = MySQLDatabase(
   host=DATABASES['DEFAULT']['HOST'],
   port=DATABASES['DEFAULT']['PORT'],
   user=DATABASES['DEFAULT']['USER'],
   passwd=DATABASES['DEFAULT']['PASSWORD'],
   database=DATABASES['DEFAULT']['NAME'],
)

class BaseModel(Model):
   """基础模型类"""

   class Meta:
       database = MYSQL_DB

class NewRecord(BaseModel):
   # 所有model都继承基类model

   field_1 = CharField(max_length=10, null=True)

   class Meta:
       db_table = 'new_record'

if __name__ == '__main__':
   # 创建表
   NewRecord.create_table()



  • 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
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

查询

new_records = NewRecord.select().where(
        NewRecord.field_1 == "").order_by(
        NewRecord.id)
  • 1
  • 2
  • 3

注意:查询条件之间的关系不是用 and 和 or 的逻辑运算符,而是用 & 和 |

查询单条数据

# 若查询不到记录会报错
_record = NewRecord.get(NewRecord.field_1 == field_1 and NewRecord.field_2 == field_2)  
print(_record.field_1, _record.field_2)


  • 1
  • 2
  • 3
  • 4
  • 5

删除

NewRecord.delete().where(NewRecord.field_1 == field_1).execute()

  • 1
  • 2

删除单条数据

_record = NewRecord.get(NewRecord.field_1 == field_1 and NewRecord.field_2 == field_2)
_record.delete_instance()
  • 1
  • 2

联合约束

class Meta:
        db_table = 'new_record'
        constraints = [SQL('UNIQUE KEY(field_1, field_2)')]
  • 1
  • 2
  • 3

默认时间

class NewRecord(BaseModel):
    """NewRecord 模型类"""
    # ...
	add_time = DateTimeField(datetime.datetime.now)

	class Meta:
        db_table = 'new_record'

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

根据数据表生成model

python -m pwiz -e mysql -H {主机地址} -p 3306  -u root -- password   {数据库名称} > {生成的代码文件 例model.py}
  • 1

查询操作符 & 逻辑运算符

符号注释
==x equals y
<x is less than y
<=x is less than or equal to y
>x is greater than y
>=x is greater than or equal to y
!=x not equals y
<<x IN y,where is a list or equal
>>x IS y,where is a None/NULL
%x LIKE y where y may conta
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/172933
推荐阅读
相关标签
  

闽ICP备14008679号