1.准备
官方链接
http://docs.peewee-orm.com/en/latest/peewee/api.html#ColumnBase
安装
pip install peewee
2.创建模型
from peewee import MySQLDatabase, Model, CharField, TextField, DateTimeField, AutoField, IntegerField, DecimalField, \
BigAutoField, FloatField
class configdata(Model):
id = AutoField(verbose_name='id', db_column='id', primary_key=True)
key = CharField(verbose_name="key", max_length=50, null=False, primary_key=True)
value = TextField(verbose_name="value", null=False)
updatetime = DateTimeField(verbose_name="更新时间")
class Meta:
database = db
3.使用
1.查询
单个查询
sql_data = configdata.get(configdata.key == 'xxx')
批量查询
configdata.filter(key__in=key_list)
2.更新
configdata.update(**item).where(configdata.key == 'xxx').execute()
批量更新
while db.atomic():# 使用事务
configdata.bulk_update(update_list, fields=fields, batch_size=32000) # update_list一个模型组成的list,fields要更新的字段,batch_size切片写入最大块
3.插入
插入
Setting.insert_many([
{'key': 'host', 'value': '192.168.1.2'},
{'key': 'port': 'value': '1337'},
{'key': 'user': 'value': 'nuggie'}]).execute()
批量插入
while db.atomic():# 使用事务
configdata.bulk_create(create_list, batch_size=32000)
4.插入或更新
configdata.replace(**item).execute()
5.删除
sql_data = configdata.get(configdata.key == 'xxx')
sql_data.delete_instance()