Peewee 是一個基於 ORM(對象-關係映射)的 Python 庫,支持 SQLite、MySQL、PostgreSQL 和蟑螂數據庫。在下面的教程中,我們將學習如何使用 Python 編程語言中的 Peewee 庫插入新記錄、刪除記錄、創建索引等等。此外,我們還將了解關於 Peewee 的連接管理、文本和二進制字段、子查詢、過濾器等等。
那麼,讓我們開始吧。
- Peewee 是美國軟件工程師 Charles Leifer 於 2010 年 10 月開發的 Python 對象關係映射(也稱為 ORM)庫。
- 這個庫的最新版本是 3.14.8。這個庫支持 SQLite、MySQL、PostgreSQL 和蟑螂的數據庫。
- 對象關係映射是一種編程方法,允許程序員在面向對象編程語言的不兼容類型系統之間轉換數據。
- 類被認為是非標量的,因為它們是在面向對象編程語言(OOPs)中定義的,比如 Python。它不能表示為像整數和字符串這樣的原始數據類型。
- 相比之下,SQLite、MySQL、Oracle 等數據庫只能存儲和操作表中排列的整數和字符串等標量值。
- 程序員應該或者將對象的值轉換成標量數據類型的集合以存儲在數據庫中,或者在檢索時將它們轉換回來,或者只在程序中使用簡單的標量值。
- 在 ORM 系統中,每個類都映射到底層數據庫中的一個表。作為我們自己編寫繁瑣的數據庫接口代碼的替代,ORM 解決了這些問題,同時我們可以專註於系統邏輯的編程。
我們可以使用如下所示的 pip 安裝程序安裝最新版本的 Peewee,該版本託管在PyPI(Python 包索引的縮寫)上:
語法:
$ pip3 install Peewee
此庫沒有其他依賴項。由於 sqlite3 模塊與標準庫捆綁在一起,因此它可以在不安裝任何其他軟件包的情況下與 SQLite 一起工作。
但是,為了使用 MySQL 和 PostgreSQL,我們可能必須分別安裝與 DB-API 兼容的驅動程序模塊——pymysql 和 pyscopg2。蟑螂數據庫是通過默認情況下與 Peewee 庫一起安裝的遊戲室擴展來處理的。
模型映射到數據庫表,字段映射到表列,實例映射到錶行。
Peewee 利用 MySQL 的 MySQLDatabase、PostgreSQL 的 PostgresqlDatabase 和 SQLite 的 SqliteDatabase。對於下面的教程,我們將使用 SQLite 數據庫。
Peewee 模型中的字段類型定義了模型的存儲類型。它們被轉換為相應的數據庫列類型。
| S.NO | 字段類型 | 數據庫 | 一種數據庫系統 | 關係型數據庫 |
| one | 夏菲爾德 | 可變長字符串 | 可變長字符串 | 可變長字符串 |
| Two | TextField | 文本 | 文本 | 長文本 |
| three | 日期時間字段 | 日期時間 | 時間戳 | 日期時間 |
| four | 整數文件 | 整數 | 整數 | 整數 |
| five | 布林欄位 | 斯莫列特 | 布爾代數學體系的 | 彎曲件 |
| six | 浮動字段 | 真實的 | 真實的 | 真實的 |
| seven | 雙場 | 真實的 | 雙倍精密度 | 雙倍精密度 |
| eight | 【big integrieffield】 | 整數 | 比吉斯本 | 比吉斯本 |
| nine | 十進制字段 | 小數 | 數字的 | 數字的 |
| Ten | PrimaryKeyField | 整數 | 連續的 | 整數 |
| Eleven | ForeignKeyField | 整數 | 整數 | 整數 |
| Twelve | 約會場 | 日期 | 日期 | 日期 |
| Thirteen | 時間域 | 時間 | 時間 | 時間 |
上表列出了 Peewee 字段類型以及相應的 SQLite、PostgreSQL 和 MySQL 列類型。
在第一個示例中,我們將創建一個簡單的數據庫表。
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
db = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = db
db_table = 'notes'
# creating table
Notes.create_table()
noteOne = Notes.create(text = 'Went to the Gym')
noteOne.save()
noteTwo = Notes.create(text = 'Went to the Cinema', created = datetime.date(2021, 12, 8))
noteTwo.save()
noteThree = Notes.create(text = 'Watered the plants', created = datetime.date(2021, 12, 8))
noteThree.save()
noteFour = Notes.create(text = 'Listened to music')
noteFour.save()
輸出:
sqlite> select * from notes;
1|Went to the Gym|2021-12-09
2|Went to the Cinema|2021-12-08
3|Watered the plants|2021-12-08
4|Listened to music|2021-12-09
說明:
在上面的代碼片段中,我們已經導入了所需的庫。然後,我們創建了一個名為‘testspace . db’的數據庫。然後我們創建了一個 Peewee 模型的類,並在其中添加了一些字段。我們為數據庫創建了數據庫表,並創建了該表。最後,我們在表中插入了條目並保存了數據庫。
我們可以使用 drop_table() 功能來刪除表格。讓我們考慮下面的例子來證明這一點。
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining the class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the drop_table() function to drop the table
Notes.drop_table()
說明:
在上面的代碼片段中,我們已經導入了所需的庫。然後,我們創建了一個名為‘testspace . db’的數據庫。然後我們為 Peewee 模型定義了一個類【注釋】,並創建了一個表。然後我們使用 drop_table() 函數來刪除該表。
Peewee 庫的insert _ multi()方法用於執行批量創建操作。
讓我們考慮下面的例子來證明這一點。
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# creating table
Notes.create_table()
# defining the data
the_data = [
{ 'text': 'Visited friends in the morning', 'created': datetime.date(2021, 12, 7) },
{ 'text': 'Worked on a Project', 'created': datetime.date(2021, 12, 10) },
{ 'text': 'Went to Shopping mall', 'created': datetime.date(2021, 12, 6) },
{ 'text': 'Listened to songs', 'created': datetime.date(2021, 12, 2) },
{ 'text': 'Watched Web series all day', 'created': datetime.date(2021, 12, 4) },
{ 'text': 'Watered the plants', 'created': datetime.date(2021, 12, 2) },
{ 'text': 'Walked for half an hour', 'created': datetime.date(2021, 12, 8) }
]
with dBase.atomic():
# using the insert_many() function to add entries in bulk
the_query = Notes.insert_many(the_data)
the_query.execute()
輸出:
sqlite> select * from notes;
1|Went to the Gym|2021-12-10
2|Went to the Cinema|2021-12-08
3|Watered the plants|2021-12-08
4|Listened to music|2021-12-10
5|Visited friends in the morning|2021-12-07
6|Worked on a Project|2021-12-10
7|Went to Shopping mall|2021-12-06
8|Listened to songs|2021-12-02
9|Watched Web series all day|2021-12-04
10|Watered the plants|2021-12-02
11|Walked for half an hour|2021-12-08
說明:
在上面的代碼片段中,我們已經導入了所需的庫。然後,我們創建了數據庫和表。後來,我們在需要填入表格的字典列表中定義了數據。然後,我們執行了批量操作,並使用原子方法將批量操作放入事務中。
Peewee 的選擇方法用於檢索已定義模型的實例。讓我們考慮下面的例子來說明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating the database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining the class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the select() function
notes = Notes.select()
print(notes)
# iterating through each row in the table
for note in notes:
print('{} on {}'.format(note.text, note.created))
輸出:
$ python fetch_data.py
SELECT "t1"."id", "t1"."text", "t1"."created" FROM "notes" AS "t1"
Went to the Gym on 2021-12-10
Went to the Cinema on 2021-12-08
Watered the plants on 2021-12-08
Listened to music on 2021-12-10
Visited friends in the morning on 2021-12-07
Worked on a Project on 2021-12-10
Went to Shopping mall on 2021-12-06
Listened to songs on 2021-12-02
Watched Web series all day on 2021-12-04
Watered the plants on 2021-12-02
Walked for half an hour on 2021-12-08
說明:
在上面的代碼片段中,我們已經導入了所需的庫。然後,我們創建了數據庫和表。然後,我們使用 select() 函數從表中選擇列。然後,我們使用的循環遍歷表中的每一行,並為用戶打印它們。結果,程序為用戶返回了條目。
Peewee 的其中方法允許程序員根據指定的條件過濾數據。讓我們考慮下面的例子來理解這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the where method to filter data
notes = Notes.select().where(Notes.id > 4)
# iterating through each row of the table
for note in notes:
print('{} {} on {}'.format(note.id, note.text, note.created))
輸出:
5 Visited friends in the morning on 2021-12-07
6 Worked on a Project on 2021-12-10
7 Went to Shopping mall on 2021-12-06
8 Listened to songs on 2021-12-02
9 Watched Web series all day on 2021-12-04
10 Watered the plants on 2021-12-02
11 Walked for half an hour on 2021-12-08
說明:
在上面的代碼片段中,我們已經導入了所需的庫,並創建了一個數據庫和表。然後,我們使用 where 方法和 select() 函數來過濾表中的數據。然後我們使用的循環遍歷表格的每一行,並為用戶打印數據。
我們可以多次使用方法,並將它們組合起來產生一個新的表達式,並精確過濾過程。讓我們考慮下面的例子來證明這一點:
**示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the where method to filter data
notes = Notes.select().where((Notes.id > 3) & (Notes.id < 10))
# iterating through each rows of the table
for note in notes:
print('{} {} on {}'.format(note.id, note.text, note.created))
輸出:
4 Listened to music on 2021-12-10
5 Visited friends in the morning on 2021-12-07
6 Worked on a Project on 2021-12-10
7 Went to Shopping mall on 2021-12-06
8 Listened to songs on 2021-12-02
9 Watched Web series all day on 2021-12-04
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。我們現在已經使用了方法,其中方法指定了限制,以便以特定的方式過濾數據。然後我們使用的循環遍歷行,並為用戶打印它們。
我們可以使用兩種方法來選擇單個實例;它們中的每一個都利用了 get() 函數。
讓我們考慮下面的例子來理解它的工作原理:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# first method
noteOne = Notes.select().where(Notes.text == 'Went to the Gym').get()
print(noteOne.id)
print(noteOne.text)
print(noteOne.created)
# second method
noteTwo = Notes.get(Notes.text == 'Worked on a Project')
print(noteTwo.id)
print(noteTwo.text)
print(noteTwo.created)
輸出:
1
Went to the Gym
2021-12-10
6
Worked on a Project
2021-12-10
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。為了檢索單個實例,我們可以使用第一種方法,在第一種方法中,我們可以使用 where 方法以及 get() 函數,或者使用第二種方法,使用 get() 函數。以上示例中顯示了這兩種方法。
我們可以在選擇方法中指定必須包含在查詢中的列的名稱。
下面是演示相同內容的示例:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the select() function
notes = Notes.select(Notes.text, Notes.created).limit(3)
output = [e for e in notes.tuples()]
print(output)
輸出:
[('Went to the Gym', datetime.date(2021, 12, 10)), ('Went to the Cinema', datetime.date(2021, 12, 8)), ('Watered the plants', datetime.date(2021, 12, 8))]
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後,我們使用 select() 函數指定必須選擇的列的名稱。我們還包括了限制功能,以限制要打印的條目數量。
我們可以使用計數方法來計算表格中模型實例的數量。讓我們考慮下面的例子來說明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the count() function
count1 = Notes.select().count()
print(count1)
count2 = Notes.select().where(Notes.created >= datetime.date(2021, 12, 7)).count()
print(count2)
輸出:
11
7
說明:
在上面的代碼片段中,我們已經導入了所需的庫,並創建了數據庫和表。然後我們使用 count() 函數來計算條目的總數。然後,我們使用了 where() 功能來指定條目選擇的限制,並再次使用了 count() 功能來僅打印所選條目的數量。
Peewee 庫提供了 sql 方法,允許程序員生成 sql 語句。
讓我們考慮下面的例子來說明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# selecting the specific entry
noteFour = Notes.select().where(Notes.id == 4)
# using the sql function
print(noteFour.sql())
輸出:
('SELECT "t1"."id", "t1"."text", "t1"."created" FROM "notes" AS "t1" WHERE ("t1"."id" = ?)', [4])
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後我們使用選擇()功能和 where() 選擇 id = 4 的條目。然後我們使用 sql 函數打印該選擇操作的 sql 語句。
Peewee 還提供了幾個屬性,如偏移和限制,允許程序員定義實例的初始跳過和要包含在選擇功能中的實例數量。
讓我們考慮下面的例子來證明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# using the offset and limit attributes
the_notes = Notes.select().offset(3).limit(4)
# iterating through the entries in the table
for note in the_notes:
print(note.id, note.text, note.created)
輸出:
4 Listened to music 2021-12-10
5 Visited friends in the morning 2021-12-07
6 Worked on a Project 2021-12-10
7 Went to Shopping mall 2021-12-06
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後我們用選擇()功能使用偏移和限制屬性,以便選擇從第 4 個條目到接下來三個條目的條目。
我們可以使用 Peeweorder _ by函數來檢索實例。讓我們考慮下面的例子來證明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
print('Ascending order')
print('********************************')
# using the order_by function. By default Ascending order
the_notes = Notes.select(Notes.text, Notes.created).order_by(Notes.created)
for note in the_notes:
print(note.text, note.created)
print()
print('Descending order')
print('********************************')
# using the order_by function along with desc() function for descending order
the_notes = Notes.select(Notes.text, Notes.created).order_by(Notes.created.desc())
for note in the_notes:
print(note.text, note.created)
輸出:
Ascending order
********************************
Listened to songs 2021-12-02
Watered the plants 2021-12-02
Watched Web series all day 2021-12-04
Went to Shopping mall 2021-12-06
Visited friends in the morning 2021-12-07
Went to the Cinema 2021-12-08
Watered the plants 2021-12-08
Walked for half an hour 2021-12-08
Went to the Gym 2021-12-10
Listened to music 2021-12-10
Worked on a Project 2021-12-10
Descending order
********************************
Went to the Gym 2021-12-10
Listened to music 2021-12-10
Worked on a Project 2021-12-10
Went to the Cinema 2021-12-08
Watered the plants 2021-12-08
Walked for half an hour 2021-12-08
Visited friends in the morning 2021-12-07
Went to Shopping mall 2021-12-06
Watched Web series all day 2021-12-04
Listened to songs 2021-12-02
Watered the plants 2021-12-02
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後,我們使用選擇功能和排序方式選擇表格中的條目並按升序排列。然後我們使用循環的循環遍歷每一行並打印它們。然後我們再次使用選擇功能和按排序。但是,我們添加了 desc() 功能,以便按照降序排列條目,並藉助於用於- 循環的為用戶打印它們。
使用 Peewee 刪除實例
Peewee 庫提供了 delete_by_id 方法,允許程序員刪除由其 id 標識的實例。此函數返回已刪除實例的數量。
讓我們考慮下面的例子來證明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# deleting the entry using ID
noteThree = Notes.delete_by_id(3)
# using the select() function
notes = Notes.select()
# iterating through each row in the table
for note in notes:
print('{} - {} on {}'.format(note.id, note.text, note.created))
輸出:
1 - Went to the Gym on 2021-12-10
2 - Went to the Cinema on 2021-12-08
4 - Listened to music on 2021-12-10
5 - Visited friends in the morning on 2021-12-07
6 - Worked on a Project on 2021-12-10
7 - Went to Shopping mall on 2021-12-06
8 - Listened to songs on 2021-12-02
9 - Watched Web series all day on 2021-12-04
10 - Watered the plants on 2021-12-02
11 - Walked for half an hour on 2021-12-08
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後我們使用 delete_by_id() 函數刪除 ID = 3 處的條目。然後我們為用戶打印了整個表格。因此, ID = 3 處的條目已成功從表中刪除。
使用 Peewee 刪除多個實例
為了刪除多個實例,我們可以調用 Peewee delete 方法。此方法將返回成功刪除的實例數。
讓我們考慮下面的例子來說明這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# deleting multiple instances
the_query = Notes.delete().where(Notes.id > 3)
num = the_query.execute()
print('{} instances deleted'.format(num))
輸出:
7 instances deleted
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後,我們使用了 delete() 方法和 where() 方法來刪除 id 在 3 以上的實例。因此,從表中刪除了七個實例。
使用 Peewee 更新實例
我們可以使用 Peewee 更新方法來更新一個實例。它返回成功更新的實例數。
下面的例子證明了這一點:
示例:
# importing the required libraries
import peewee
import datetime
# creating a database
dBase = peewee.SqliteDatabase('testSpace.db')
# defining a class as Notes
class Notes(peewee.Model):
text = peewee.CharField()
created = peewee.DateField(default = datetime.date.today)
class Meta:
database = dBase
db_table = 'notes'
# updating an instance
the_query = Notes.update(created=datetime.date(2021, 10, 27)).where(Notes.id == 2)
num = the_query.execute()
print('No. of rows updated: {}'.format(num))
輸出:
No. of rows updated: 1
說明:
我們已經導入了所需的庫,並在上面的代碼片段中創建了數據庫和表。然後我們使用 update() 函數在 ID = 2 處更新實例的日期。
原創文章,作者:0W7J5,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/126688.html