赞
踩
通过 pip instll peewee
新建 models.py 模型文件
在 models.py 中加入以下基础代码
运行 models.py,在 mysql 中生成 new_record 表
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()
new_records = NewRecord.select().where(
NewRecord.field_1 == "").order_by(
NewRecord.id)
注意:查询条件之间的关系不是用 and 和 or 的逻辑运算符,而是用 & 和 |
# 若查询不到记录会报错
_record = NewRecord.get(NewRecord.field_1 == field_1 and NewRecord.field_2 == field_2)
print(_record.field_1, _record.field_2)
NewRecord.delete().where(NewRecord.field_1 == field_1).execute()
_record = NewRecord.get(NewRecord.field_1 == field_1 and NewRecord.field_2 == field_2)
_record.delete_instance()
class Meta:
db_table = 'new_record'
constraints = [SQL('UNIQUE KEY(field_1, field_2)')]
class NewRecord(BaseModel):
"""NewRecord 模型类"""
# ...
add_time = DateTimeField(datetime.datetime.now)
class Meta:
db_table = 'new_record'
python -m pwiz -e mysql -H {主机地址} -p 3306 -u root -- password {数据库名称} > {生成的代码文件 例model.py}
符号 | 注释 |
---|---|
== | 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 |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。