Python轻量级ORM框架peewee入门教程

Ruby
Ruby
发布时间:2026-10-14| 6人浏览过
原创

本文介绍Python轻量级ORM框架peewee的安装与核心功能。相比SQLAlchemy和Django ORM,peewee语法简洁且资源占用极低。教程涵盖从环境配置、MySQL驱动处理到建表、增删改查及批量查询的完整代码示例,适合追求轻量级解决方案的开发者。

在Python生态中,ORM框架的使用十分普遍,其中SQLAlchemy和Django内置的ORM框架应用最为广泛。相比之下,SQLAlchemy的语法结构相对Django自带的ORM框架而言,显得更为繁琐复杂。

Django本身是一个重量级的Web框架,如果仅仅为了使用其ORM功能而安装整个Django环境,会导致系统资源冗余臃肿。peewee框架则提供了几乎与Django ORM一致的语法体验,同时保持了极高的轻量级特性,是更优的选择。

安装peewee的过程非常简便,只需执行以下命令即可:


pip install peewee

如果在连接MySQL数据库时遇到如下报错信息:


peewee.ImproperlyConfigured: MySQL driver not installed!

这表明需要额外安装MySQL的驱动程序,可通过以下命令解决:


pip install pymysql

值得注意的是,peewee的whl安装包大小仅为880kB,而pymysql的whl包更是只有51KB,两者结合依然保持了非常轻量级的特点。

peewee的官方文档提供了详细的使用指南,访问地址为:http://docs.peewee-orm.com/en/latest/index.html

接下来,我们将通过实际代码测试peewee的各项核心功能。


from peewee import *

db = MySQLDatabase('test', host="localhost", user='root', passwd='123456', port=3306)


# 定义Person
class Person(Model):
  name = CharField()
  birthday = DateField()
  is_relative = BooleanField()

  class Meta:
    database = db
    
def test_create():
  Person.create_table()
  # 创建多张表也可以这样
  # database.create_tables([Person])


def test_insert():
  # 添加一条数据
  p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=True)
  p.save()


def test_delete():
  # 删除姓名为perter的数据
  Person.delete().where(Person.name == 'perter').execute()
  # 已经实例化的数据, 使用delete_instance
  p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=False)
  p.id = 1
  p.save()
  p.delete_instance()


def test_update():
  # 已经实例化的数据,指定了id这个primary key,则此时保存就是更新数据
  p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=False)
  p.id = 1
  p.save()

  # 更新birthday数据
  q = Person.update({Person.birthday: date(1983, 12, 21)}).where(Person.name == '小华')
  q.execute()


def test_query():
  # 查询单条数据
  p = Person.get(Person.name == '小华')
  print(p.name, p.birthday, p.is_relative)

  # 使用where().get()查询
  p = Person.select().where(Person.name == '小华').get()
  print(p.name, p.birthday, p.is_relative)

  # 查询多条数据
  persons = Person.select().where(Person.is_relative == True)
  for p in persons:
    print(p.name, p.birthday, p.is_relative)

下面将逐一演示各个常用方法的具体用法。

首先测试创建数据库表的功能:


if __name__=="__main__":
  Person.create_table()

执行上述代码后,检查数据库可以发现已成功创建了相应的数据表。

接下来测试向表中插入数据的操作:


if __name__=="__main__":
  p = Person(name='小华', birthday=date(1996, 12, 20), is_relative=True)
  p.save()

代码执行完毕后,数据库表中将新增一行记录。

随后测试从数据库中查询数据的功能:


if __name__=="__main__":
 p = Person.get(Person.name == '小华')
  print(p.name, p.birthday, p.is_relative)

查询结果如下所示:


小华 1996-12-20 True

接着测试删除数据库中指定数据的功能:


if __name__=="__main__":
  Person.delete().where(Person.name == '小华').execute()

执行删除操作后,数据库中对应的记录将被成功移除。

最后测试修改现有数据的功能:


if __name__ == "__main__":
  p = Person(name='小新', birthday=date(1995, 6, 20), is_relative=False)
  p.save()
  # 更新birthday数据
  q = Person.update({Person.birthday: date(1983, 5, 21)}).where(Person.name == '小新')
  q.execute()

此外,peewee还支持批量查询操作,示例如下:


if __name__ == "__main__":
  for i in range(1, 5):
    p = Person(name=f'小张{i}', birthday=date(1995, 6, 20), is_relative=False)
    p.save()
  # 查询多条数据
  persons = Person.select().where(Person.is_relative == False)
  for p in persons:
    print(p.name, p.birthday, p.is_relative)

以上便是Python轻量级ORM框架peewee的详细使用教程,更多关于Python轻量级ORM框架peewee的资料,欢迎持续关注本站的其他相关文章。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。