赞
踩
Peewee 即 Python OMR 框架之一。
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):
"""NewRecord 模型类"""
field_1 = CharField(max_length=10, null=True)
field_2 = CharField(max_length=100, null=True)
field_3 = IntegerField(default=0)
field_4 = TextField()
class Meta:
db_table = 'new_record'
if __name__ == '__main__':
# 创建表
NewRecord.create_table()
new_record = NewRecord()
new_record.field_1 = "field_1"
new_record.field_2 = "field_2"
new_record.field_3 = 0
new_record.field_4 = "field_4"
new_record.save()
from modules.models import NewRecord def get_data_list(): """获取数据列表 :return: """ data_list = [] new_records = NewRecord.select().where( NewRecord.status == 0).order_by( NewRecord.id) for new_record in new_records: _data = { 'field_1': new_record.field_1, 'field_2': new_record.field_2, 'field_3': new_record.field_3 } data_list.append(_data) return data_list
注意:过滤条件之间的关系不是用 and 和 or 的逻辑运算符,而是用 & 和 |。
Record.select().where(
(Record.field_1 == value_1) &
(Record.field_2 == value_2))
def update_new_record_field_3( field_1, field_2, field_3): """更新特定查询数据字段 field_3 :param field_1: 待更新 field_1 :param field_2: 待更新 field_2 :param field_3: 待更新 field_3 :return: """ update_instance = NewRecord.update( { NewRecord.field_3: field_3 } ).where(NewRecord.field_1 == field_1 and NewRecord.field_2 == field_2) update_instance.execute()
# 若查询不到记录会报错
_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}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。