peewee 通俗易懂版
生活随笔
收集整理的這篇文章主要介紹了
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
總結
以上是生活随笔為你收集整理的peewee 通俗易懂版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: App过大
- 下一篇: 华夏银行信用卡宽限期有几天?还款的相关信