Python簡潔強大的ORM框架Peewee的用法詳解
在 Python
的開發(fā)世界中,數(shù)據(jù)庫操作是至關(guān)重要的一環(huán)。
今天介紹的 Peewee
作為一款簡潔且功能強大的 ORM
(對象關(guān)系映射)框架,為開發(fā)者提供了高效便捷的數(shù)據(jù)庫交互方式。
1. Peewee概述
Peewee
是一個簡單小巧的 ORM
,它的概念簡潔明了,易于學(xué)習(xí)和使用。
能夠與 SQLite
、MySQL
、MariaDB
、PostgreSQL
等多種數(shù)據(jù)庫協(xié)同工作,擁有豐富的擴展功能,其源代碼托管于 GitHub-peewee。
使用過Python
的都知道,SQLAlchemy
幾乎已經(jīng)是Python
中的標準ORM
框架了,功能強大,
為什么還要使用Peewee
呢?
首先,Peewee
設(shè)計更為簡潔,其 API 簡單直觀,學(xué)習(xí)曲線平緩,新手能快速上手,而 SQLAlchemy
相對復(fù)雜,需要花費更多時間去掌握。
其次,Peewee
代碼量較少,在一些簡單項目中,其輕量級的特點能使項目結(jié)構(gòu)更清晰,開發(fā)效率更高。
例如在小型數(shù)據(jù)庫應(yīng)用場景下,Peewee
能快速搭建起數(shù)據(jù)操作模塊。
再者,Peewee
的性能在特定場景下表現(xiàn)出色,如對 SQLite
數(shù)據(jù)庫的操作,其資源占用相對較低,能為應(yīng)用帶來更好的運行效果。
總之,如果項目規(guī)模不大,或者做一些小工具,那么Peewee
會更加趁手。
2. 快速上手
2.1. 初始化數(shù)據(jù)庫
針對不同的數(shù)據(jù)庫類型,有相應(yīng)的初始化方式。
下面我們選擇使用SQLite
:
from peewee import SqliteDatabase db = SqliteDatabase('my_database.db')
2.2. 模型定義
在 Peewee
中,通過定義類來創(chuàng)建模型,類的屬性對應(yīng)數(shù)據(jù)庫表中的字段。例如:
from peewee import Model, CharField, IntegerField class User(Model): class Meta: database = db username = CharField(unique=True) age = IntegerField()
2.3. 創(chuàng)建數(shù)據(jù)庫和表
連接數(shù)據(jù)庫,然后就可通過SqliteDatabase
來創(chuàng)建表。
if __name__ == "__main__": db.connect() db.create_tables([User])
執(zhí)行之后,就會發(fā)現(xiàn)創(chuàng)建了sqlite數(shù)據(jù)庫和表。
$ sqlite3.exe .\my_database.db
SQLite version 3.45.3 2024-04-15 13:34:05 (UTF-16 console I/O)
Enter ".help" for usage hints.
sqlite> .tables
user
db.create_tables
反復(fù)執(zhí)行也沒關(guān)系,如果表已經(jīng)存在,不會重復(fù)創(chuàng)建。
2.4. 數(shù)據(jù)存儲與檢索
存儲數(shù)據(jù)時,先創(chuàng)建模型實例并賦值,然后調(diào)用 save
方法即可將數(shù)據(jù)保存到數(shù)據(jù)庫。
if __name__ == "__main__": user = User(username="Harry", age=23) user.save()
運行之后,查詢數(shù)據(jù)庫,發(fā)現(xiàn)數(shù)據(jù)已經(jīng)寫入了數(shù)據(jù)庫。
sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1 │ Harry │ 23 │
└────┴──────────┴─────┘
檢索數(shù)據(jù)可以使用各種查詢方法。如獲取單個記錄:
user = User.get(User.username == "Harry") print(f"name: {user.username}, age: {user.age}") # 運行結(jié)果: # name: Harry, age: 23
2.5. 更新記錄
更新記錄,比如將上面的年齡改為30。
User.update(age=30).where(User.username == 'Harry').execute()
運行之后:
sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1 │ Harry │ 30 │
└────┴──────────┴─────┘
2.6. 刪除記錄
刪除記錄也很簡單:
User.delete().where(User.username == 'Harry').execute()
運行之后:
sqlite> select * from user;
sqlite> select count(1) from user;
┌──────────┐
│ count(1) │
├──────────┤
│ 0 │
└──────────┘
3. 高級查詢功能
高級的查詢功能包括多條件過濾,排序以及分頁查詢等等。
3.1. 批量插入數(shù)據(jù)
為了演示高級查詢功能,先批量插入一批數(shù)據(jù)。
User.insert_many(users, fields=[User.username, User.age]).execute()
運行結(jié)果:
sqlite> select * from user;
┌────┬──────────┬─────┐
│ id │ username │ age │
├────┼──────────┼─────┤
│ 1 │ harry │ 23 │
│ 2 │ lily │ 20 │
│ 3 │ tom │ 35 │
│ 4 │ jerry │ 12 │
│ 5 │ kate │ 42 │
└────┴──────────┴─────┘
3.2. 多條件查詢
多個條件的交集,比如id>2
并且age>30
的數(shù)據(jù):
users = User.select().where((User.id > 2) & (User.age > 30)).execute() print("滿足條件的用戶:") for u in users: print(f"{u.username}: {u.age}")
運行結(jié)果:
$ python.exe .\main.py
滿足條件的用戶:
tom: 35
kate: 42
多個條件的并集,比如id>4
或者age>20
的數(shù)據(jù):
users = User.select().where((User.id > 4) | (User.age > 20)).execute()
運行結(jié)果:
$ python.exe .\main.py
滿足條件的用戶:
harry: 23
tom: 35
kate: 42
3.3. 排序
按照年齡增長排序:
users = User.select().order_by(User.age)
運行結(jié)果:
$ python.exe .\main.py
按照年齡增長排序:
jerry: 12
lily: 20
harry: 23
tom: 35
kate: 42
按照年齡減少方向排序:
users = User.select().order_by(User.age.desc())
運行結(jié)果:
$ python.exe .\main.py
按照年齡減少排序:
kate: 42
tom: 35
harry: 23
lily: 20
jerry: 12
3.4. 分頁查詢
最后,再來看看分頁查詢,這在前端展示大規(guī)模數(shù)據(jù)時非常有用。
一般的ORM
會通過SQL
語句中的limit
和offset
來實現(xiàn)分頁查詢,而Peewee
直接提供了分頁查詢的API。
page_number = 1 # 頁序號,從1開始 page_size = 3 # 每頁數(shù)據(jù)的數(shù)量 users = User.select().paginate(page_number, page_size) print(f"第{page_number}頁數(shù)據(jù):") for u in users: print(f"{u.username}: {u.age}")
運行結(jié)果:
$ python.exe .\main.py
第1頁數(shù)據(jù):
harry: 23
lily: 20
tom: 35
這樣就顯示了前3個數(shù)據(jù),如果把上面的page_numberg=2
,那么會返回剩下的2條數(shù)據(jù)。
4. 總結(jié)
Peewee
還擁有眾多擴展,如 Playhouse
提供了更多高級功能,包括對不同數(shù)據(jù)庫的特定擴展(如 SQLite
的擴展函數(shù))、模型生成工具、數(shù)據(jù)庫遷移工具、反射功能等,大大增強了 Peewee
的實用性和靈活性。
本篇介紹的是最基本的使用方法,其他還有多表之間關(guān)系的建立和查詢,請參考官方的文檔。
總之,Peewee
以其簡潔的語法、豐富的功能和良好的擴展性,成為 Python
開發(fā)者在數(shù)據(jù)庫操作方面的有力工具,無論是小型項目還是大型應(yīng)用,都能提供高效可靠的數(shù)據(jù)庫交互支持。
到此這篇關(guān)于Python簡潔強大的ORM框架Peewee的用法詳解的文章就介紹到這了,更多相關(guān)Python Peewee內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Scrapy之爬取結(jié)果導(dǎo)出為Excel的實現(xiàn)過程
這篇文章主要介紹了Scrapy之爬取結(jié)果導(dǎo)出為Excel的實現(xiàn)過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Python創(chuàng)建對稱矩陣的方法示例【基于numpy模塊】
這篇文章主要介紹了Python創(chuàng)建對稱矩陣的方法,結(jié)合實例形式分析了Python基于numpy模塊實現(xiàn)矩陣運算的相關(guān)操作技巧,需要的朋友可以參考下2017-10-10