Python Peewee库
Peewee 是一个基于ORM(对象关系映射)的Python库,支持SQLite、MySQL、PostgreSQL和Cockroach数据库。在以下教程中,我们将学习如何使用Python编程语言中的Peewee库插入新记录、删除记录、创建索引等等。此外,我们还将了解关于Peewee的连接管理、文本和二进制字段、子查询、过滤器等等。
所以,让我们开始吧。
了解Python中的Peewee库
- Peewee是由美国软件工程师Charles Leifer于2010年10月开发的Python对象关系映射(简称ORM)库。
- 这个库的最新版本是3.14.8。该库支持SQLite、MySQL、PostgreSQL和Cockroach数据库。
- 对象关系映射是一种编程方法,允许程序员在面向对象编程语言中在不兼容的类型系统之间转换数据。
- 类被认为是不可标量的,因为它们在面向对象编程语言(OOP)中定义。它不能被表示为像整数和字符串这样的原始数据类型。
- 相反,诸如SQLite、MySQL、Oracle等数据库只能存储和操作表格中的标量值,如整数和字符串。
- 程序员应该将对象的值转换为标量数据类型的集合以存储在数据库中,或者在检索时将它们转换回来,或者仅在程序内部使用简单的标量值。
- 在ORM系统中,每个类都映射到底层数据库中的一个表。ORM代替我们编写冗长的数据库接口代码,而我们可以专注于编写系统逻辑。
设置环境
我们可以使用pip安装程序安装托管在 PyPI (Python Package Index)上的最新版本Peewee,如下所示:
语法:
$ pip3 install Peewee
此库无需其他依赖即可工作。它与SQLite一起工作,无需安装任何其他软件包,因为sqlite3模块已与标准库捆绑在一起。
然而,为了使用MySQL和PostgreSQL,我们可能需要安装DB-API兼容的驱动程序模块 – 分别是pymysql和pyscopg2。Cockroach数据库是通过与Peewee库一起默认安装的playhouse扩展处理的。
使用Peewee理解映射
模型映射到数据库表,字段映射到表列,实例映射到表行。
Peewee使用MySQLDatabase进行MySQL,PostgresqlDatabase进行PostgreSQL,SqliteDatabase进行SQLite。在接下来的教程中,我们将使用SQLite数据库。
Peewee中的字段类型理解
Peewee模型中的字段类型定义了模型的存储类型。它们被翻译为相应的数据库列类型。
S.NO | Field Type | SQLite | PostgreSQL | MySQL |
---|---|---|---|---|
1 | CharField | Varchar | Varchar | Varchar |
2 | TextField | Text | Text | Longtext |
3 | DateTimeField | Datetime | Timestamp | Datetime |
4 | IntegerField | Integer | Integer | Integer |
5 | BooleanField | Smallint | Boolean | Bool |
6 | FloatField | Real | Real | Real |
7 | DoubleField | Real | Double Precision | Double Precision |
8 | BigIntegerField | Integer | Bigint | Bigint |
9 | DecimalField | Decimal | Numeric | Numeric |
10 | PrimaryKeyField | Integer | Serial | Integer |
11 | ForeignKeyField | Integer | Integer | Integer |
12 | DateField | Date | Date | Date |
13 | TimeField | Time | Time | Time |
上表列出了Peewee字段类型及其对应的SQLite、PostgreSQL和MySQL列类型。
使用Peewee定义模型
在第一个示例中,我们将创建一个简单的数据库表。
示例:
# 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模型的类,并添加了一些字段。我们为数据库创建了数据库表并创建了该表。最后,我们向表中插入了条目并保存了数据库。
使用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’ 的数据库。然后我们定义了一个名为 ‘Notes’ 的类作为Peewee模型并创建了一个表。然后,我们使用 drop_table() 函数来删除表。
Peewee insert_many()方法
Peewee库的 insert_many() 方法用于执行批量创建操作。
让我们考虑下面的示例来演示相同的操作。
示例:
# 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选择所有实例
使用Peewee的 select 方法可以检索定义的模型的实例。让我们考虑下面的示例来说明这一点:
示例:
# 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() 函数从表中选择列。然后我们使用 for 循环来遍历表中的每一行并打印出来供用户查看。结果,程序返回了用户的条目。
使用Peewee where方法进行数据过滤
Peewee的 where 方法允许程序员根据指定条件来过滤数据。让我们考虑以下示例来理解相同的情况:
示例:
# 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
说明:
在上述的代码片段中,我们引入了所需的库并创建了一个数据库和表。然后,我们使用 select() 函数以及where方法来过滤表中的数据。接下来,我们使用 for 循环来遍历表中的每一行并打印用户数据。
Peewee多个where表达式
我们可以多次使用where方法,并将它们组合在一起生成新的表达式,从而精确地进行筛选。让我们看下面的示例来说明这一点:
示例:
# 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
解释:
我们在上面的代码片段中导入了所需的库并创建了数据库和表。我们现在使用了 where 方法指定限制条件以便以特定方式筛选数据。然后我们使用了 for 循环遍历行并将它们打印给用户。
使用Peewee检索单个实例
有两种方法可以选择单个实例;每种方法都使用了 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() 函数,上面的示例中都展示了这两种方法。
使用Peewee选择列
我们可以在查询中使用 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 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() 函数指定要选择的列的名称。我们还包括了 limit 函数以限制要打印的条目数。
使用Peewee计算实例数
我们可以使用 count 方法来计算表中模型实例的数量。让我们考虑以下说明相同的示例:
示例:
# 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语句
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])
解释:
在上面的代码片段中,我们导入了所需的库并创建了数据库和表。然后我们使用了 select() 函数和 where() 函数来选择id = 4的条目。然后我们使用 sql 函数打印出该选择操作的SQL语句。
Peewee的偏移和限制属性
Peewee还提供了一些属性,如 offset 和 limit ,允许程序员定义实例的初始跳过和在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 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
解释:
我们已经导入了所需的库并在上面的代码片段中创建了数据库和表格。然后我们使用了 offset 和 limit 属性,通过 select() 函数选择了从第四个条目到后面三个条目的条目。
使用Peewee进行排序
我们可以使用Peewee order_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
解释:
在上面的代码片段中,我们导入了所需的库,并创建了数据库和表。然后我们使用了 select 函数和 order_by 方法来选择表中的条目并按升序排列。然后我们使用了 for 循环遍历每一行并打印它们。然后我们再次使用了 select 函数和 order_by 方法。然而,这次我们添加了 desc() 函数以便按降序排列条目并通过 for 循环打印给用户。
使用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的 update 方法来更新实例。它返回成功更新的实例数量。
以下是示例:
示例:
# 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的实例的日期。