python peewee orm示例
安裝Peewee 使用pip install peewee;2. 定義User 和Post 模型並綁定SQLite 數據庫;3. 調用create_tables() 創建數據表;4. 使用create() 或save() 插入數據;5. 通過select()、get()、where() 等方法實現查詢,支持條件、模糊和關聯查詢;6. 更新數據可直接修改實例後save() 或使用update().execute() 批量更新;7. 刪除使用delete_instance(),需注意外鍵級聯需顯式設置on_delete='CASCADE';8. 事務操作使用db.atomic() 包裹確保原子性;操作完成後應妥善管理數據庫連接,適合中小型項目快速開發,總結完畢。
使用Peewee ORM 操作數據庫非常簡單,適合中小型項目。下面是一個完整的Python Peewee ORM 示例,涵蓋模型定義、增刪改查(CRUD)操作,使用SQLite 作為數據庫。

? 1. 安裝Peewee
pip install peewee
?️ 2. 定義模型(Model)
假設我們要管理一個博客系統的用戶和文章。
from peewee import * # 創建數據庫連接(SQLite) db = SqliteDatabase('blog.db') class User(Model): username = CharField(unique=True) email = CharField() active = BooleanField(default=True) created_at = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')]) class Meta: database = db # 綁定數據庫class Post(Model): title = CharField() content = TextField() user = ForeignKeyField(User, backref='posts') # 用戶的posts 屬性可訪問文章created_at = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')]) class Meta: database = db
? 3. 創建表
def create_tables(): with db: db.create_tables([User, Post])
調用一次即可:

create_tables()
➕ 4. 插入數據(Create)
# 創建用戶user = User.create(username='alice', email='alice@example.com') # 或者user2 = User(username='bob', email='bob@example.com') user2.save() # 創建文章post = Post.create( title='First Post', content='Hello, this is my first blog post!', user=user )
? 5. 查詢數據(Read)
# 獲取所有用戶for user in User.select(): print(user.username, user.email) # 查詢單個用戶try: user = User.get(User.username == 'alice') print(user.email) except User.DoesNotExist: print("User not found") # 查詢某個用戶的所有文章for post in user.posts: print(post.title, post.content) # 條件查詢active_users = User.select().where(User.active == True) for u in active_users: print(u.username) # 模糊查詢users_with_a = User.select().where(User.username.contains('a'))
?️ 6. 更新數據(Update)
# 更新單個字段user.email = 'alice_new@example.com' user.save() # 批量更新User.update(active=False).where(User.username == 'bob').execute()
?️ 7. 刪除數據(Delete)
# 刪除一篇文章post = Post.get(Post.title == 'First Post') post.delete_instance() # 刪除用戶(會級聯刪除相關文章,如果外鍵設置了cascade) user.delete_instance()
⚠️ 注意:默認外鍵不啟用級聯刪除。如需啟用,定義外鍵時加上:
user = ForeignKeyField(User, backref='posts', on_delete='CASCADE')
? 8. 使用事務(可選)
with db.atomic(): User.create(username='charlie', email='charlie@example.com') Post.create(title='New Post', content='...', user=user)
✅ 小結:常用操作一覽
操作 | 示例 |
---|---|
插入 |
User.create(name='x') 或model.save()
|
查詢 | User.select().where(...) |
獲取單條 | User.get(User.id == 1) |
更新 | query = User.update(...).where(...).execute() |
刪除 | instance.delete_instance() |
關聯查詢 |
ForeignKeyField backref
|
基本上就這些。 Peewee 輕量、直觀,特別適合快速開發小項目或腳本中使用數據庫。不復雜但容易忽略細節,比如db.connect()
和db.close()
在Web 應用中要手動管理連接(Flask/Django 集成時需注意)。

以上是python peewee orm示例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

UseSublimeText’sbuildsystemtorunPythonscriptsandcatcherrorsbypressingCtrl Baftersettingthecorrectbuildsystemorcreatingacustomone.2.Insertstrategicprint()statementstocheckvariablevalues,types,andexecutionflow,usinglabelsandrepr()forclarity.3.Installth

確保已安裝Python並將其添加到系統PATH,通過終端運行python--version或python3--version驗證;2.將Python文件保存為.py擴展名,如hello.py;3.在SublimeText中創建自定義構建系統,Windows用戶使用{"cmd":["python","-u","$file"]},macOS/Linux用戶使用{"cmd":["python3

要調試Python腳本,需先安裝Python擴展並配置解釋器,然後創建launch.json文件設置調試配置,接著在代碼中設置斷點並按F5啟動調試,腳本將在斷點處暫停,允許檢查變量和單步執行,最終通過查看控制台輸出、添加日誌或調整參數等方式排查問題,確保環境正確後調試過程簡單高效。

toAutomation formatemationalformatpytpythoncodeinvscode,installblackusingpipinstallblack,installtheofficialmicrosoftpythonextension,setblackastheformatterinsettings.jsonwith“ python.formatting.formatting.provider”

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

yield關鍵字用於定義生成器函數,使其能暫停執行並逐個返回值,之後從暫停處恢復;生成器函數返回生成器對象,具有惰性求值特性,可節省內存,適用於處理大文件、流數據和無限序列等場景,且生成器是迭代器,支持next()和for循環,但無法倒回,必須重新創建才能再次迭代。

asyncio.Queue是用於異步任務間安全通信的隊列工具,1.生產者通過awaitqueue.put(item)添加數據,消費者用awaitqueue.get()獲取數據;2.每處理完一項需調用queue.task_done(),以便queue.join()等待所有任務完成;3.使用None作為結束信號通知消費者停止;4.多個消費者時,需發送多個結束信號或在取消任務前確保所有任務已處理完畢;5.隊列支持設置maxsize限制容量,put和get操作自動掛起不阻塞事件循環,程序最終通過canc

InstallSublimeTextandPython,thenconfigureabuildsystembycreatingaPython3.sublime-buildfilewiththeappropriatecmdandselectorsettingstoenablerunningPythonscriptsviaCtrl B.2.OrganizeyourprojectbycreatingadedicatedfolderwithPythonfilesandsupportingdocument
