peewee 通俗易懂版

Peewee作为Python ORM之一

优势:简单,小巧,易学习,使用直观

不足之处:需要手动创建数据库

基本使用流程

1⃣️根据需求定义好Model(表结构类)

2⃣️通过create_tables()创建表

示例:

 1 from peewee import *
 2 
 3 # 连接数据库
 4 database = MySQLDatabase('test', user='root', host='localhost', port=3306)
 5 
 6 # 定义Person
 7 class Person(Model):
 8     name = CharField()
 9     birthday = DateField()
10     is_relative = BooleanField()
11 
12     class Meta:
13         database = database
# 创建表
Person.create_table()
# 创建多个表
# database.create_tables([Person,...])

  技巧:已经创建好数据库表了,可以通过python -m pwiz脚本工具直接创建Model

# 指定mysql,用户为root,host为localhost,数据库为test
python -m pwiz -e mysql -u root -H localhost --password test > xModel.py
 1 from peewee import *
 2 
 3 database = MySQLDatabase('test', **{'charset': 'utf8', 'use_unicode': True, 'host': 'localhost', 'user': 'root', 'password': ''})
 4 
 5 class UnknownField(object):
 6     def __init__(self, *_, **__): pass
 7 
 8 class BaseModel(Model):
 9     class Meta:
10         database = database
11 
12 class Person(BaseModel):
13     birthday = DateField()
14     is_relative = IntegerField()
15     name = CharField()
16 
17     class Meta:
18         table_name = 'person'

PS关于数据类型:
CharField、DateField、BooleanField等这些类型与数据库中的数据类型一一对应,
我们直接使用它就行,至于CharField => varchar(255)这种转换Peewee已经为我们做好了。

增删改查操作:
一、增/插入数据
实例化一个Model
插入到数据库

1⃣️save()方法
# 插入一条数据
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=True)
p.save()

  2⃣️insert()方法

# 插入一条数据
p_id = Person.insert({
    'name': 'xxx'
}).execute()

 # 打印出新插入数据的id
print(p_id)

会返回新插入数据的主键

    3⃣️insert_many() 多条插入

NUM = 10000
data = [{
            'name': 'xxx'
        } for i in range(NUM)]

with database.atomic():  #事务
    for i in range(0, NUM, 100): 
        # 每次批量插入100条,分成多次插入
        Person.insert_many(data[i:i + 100]).execute()
二、查/查询数据
1⃣️get()获取单条数据
# 查询name为xxx的Person
p = Person.get(Person.name == 'xxx')
print(p.name) # 打印

   2⃣️select()查询多条数据

# 查询Person整张表的数据
persons = Person.select()
# 遍历数据
for p in persons:
    print(p.name, p.birthday, p.is_relative)

  3⃣️where()当做查询条件

# 获取is_relative为True的数据
persons = Person.select().where(Person.is_relative == True)
for p in persons:
    print(p.name, p.birthday, p.is_relative)

通过sql()方法转换为SQL语句进行查看理解
persons = Person.select().where(Person.is_relative == True)
print(persons.sql())
# 打印出的结果为:('SELECT `t1`.`id`, `t1`.`name`, `t1`.`is_relative` FROM `Person` AS `t1` WHERE (`t1`.`is_relative` = %s)', [True])

   4⃣️count()数据条数 order_by()排序 limit()限制数量

# 查询整张表的数据条数
total_num = Person.select().count()

# 查询name为xxx的Person数量, 返回数量
num = Person.select().where(Person.name == 'xxx').count()


# 按照主键id降序排序
persons = Person.select().order_by(Person.id.desc())

# 按照主键id升序排序
persons = Person.select().order_by(Person.id.asc())


# 相当于sql语句: select * from person order by id desc limit 5
persons = Person.select().order_by(Person.id.asc()).limit(5)

# 相当于sql语句中:select * from person order by id desc limit 2, 5
persons = Person.select().order_by(Person.id.asc()).limit(5).offset(2)
三、改/更新数据
1⃣️当一个Model实例拥有主键时,此时使用save()就是修改数据
# 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=False)
p.id = 1
p.save()

2⃣️update()来更新数据,一般会搭配where()使用
# 更新birthday数据
q = Person.update({Person.birthday: date(1993, 1, 19)}).where(Person.name == 'xxx')
q.execute()

q = Person.update({
    'birthday': date(1993, 1, 19)
}).where(Person.name == 'xxx')
q.execute()
 
四、删/删除数据
1⃣️delete() + where()
# 删除姓名为xxx的数据
Person.delete().where(Person.name == 'xxx').execute()

  2⃣️delete_instance()

# 已经实例化的数据, 使用delete_instance
p = Person(name='xxx', birthday=date(1993, 1, 20), is_relative=False)
p.id = 1
p.save()
p.delete_instance()
五、常用查询操作符
1⃣️容易理解
==、<、<=、>、>=、!=
等于、小于、小于等于、大于、大于等于、不等于
2⃣️需要关注

  <<>> 和 %

# <<使用,查询省份属于河北和河南的,对应sql语句:select * from person where province in ('河南', '河北')
persons = Person.select().where(Person.province << ['河南', '河北'])

# >>使用,查询省份为空的,sql语句: select * from person where province is Null
persons = Person.select().where(Person.province >> None)

# %使用,查询省份中含有 湖 字,sql语句:select * from person where province like '%湖%'
persons = Person.select().where(Person.province % '%湖%')
六、联表查询
query = (
Person.select(Person.content, Person.timestamp, Person.username)
          .join(User, on=(User.id ==Person.user_id)
)

for person in query:
    print(person.content, person.timestamp, person.user.username)
 
换句话说就是:
将person里的user_id 绑定成一个‘User属性’,
查询时候直接当作一个属性对象拿取
person.user.username
七、事务
Database.atomic()方法

from xModels import XUser, database

with database.atomic() as transaction:
    XUser.create(phone='xxxxxxxxxxx', password='123456')
    XUser.create(phone='xxxxxxxxxx$', password='654321')

参考:http://docs.peewee-orm.com/en/latest/peewee/querying.html#querying

   

 

猜你喜欢

转载自www.cnblogs.com/cutesnow/p/10626046.html