Encode ORM 查询操作完全指南:从基础到高级应用
orm An async ORM. 🗃 项目地址: https://gitcode.com/gh_mirrors/orm/orm
前言
在现代Python Web开发中,ORM(对象关系映射)技术已成为数据库操作的标配。Encode ORM作为一款轻量级异步ORM框架,提供了简洁而强大的查询接口。本文将全面解析Encode ORM的查询操作体系,帮助开发者掌握从基础查询到高级应用的各类技巧。
模型定义基础
在开始查询前,我们需要先定义数据模型。以下是一个典型的Note模型示例:
import databases
import orm
database = databases.Database("sqlite:///db.sqlite")
models = orm.ModelRegistry(database=database)
class Note(orm.Model):
tablename = "notes"
registry = models
fields = {
"id": orm.Integer(primary_key=True),
"text": orm.String(max_length=100),
"completed": orm.Boolean(default=False),
}
这个模型定义了三个字段:自增ID、文本内容和完成状态标志。
查询方法分类
Encode ORM的查询方法可分为两大类:
- 返回QuerySet的方法:可链式调用,如
.filter()
、.order_by()
- 返回结果的方法:作为查询终点,如
.all()
、.get()
返回QuerySet的方法详解
1. 排除查询 - exclude()
exclude()
方法用于排除符合条件的数据:
# 排除未完成的笔记
notes = await Note.objects.exclude(completed=False).all()
2. 条件过滤 - filter()
filter()
是最常用的查询方法,支持两种风格的条件表达式:
Django风格查询
# 查找已完成笔记
notes = await Note.objects.filter(completed=True).all()
# 查找文本包含"mum"(不区分大小写)的笔记
notes = await Note.objects.filter(text__icontains="mum").all()
# 查找ID在指定列表中的笔记
notes = await Note.objects.filter(id__in=[1, 2, 3]).all()
支持的特殊操作符包括:
in
:SQL IN操作符exact
/iexact
:精确匹配(区分/不区分大小写)contains
/icontains
:包含匹配(区分/不区分大小写)lt
/lte
:小于/小于等于gt
/gte
:大于/大于等于
SQLAlchemy风格查询
# 使用SQLAlchemy的contains方法
notes = await Note.objects.filter(Note.columns.text.contains("mum")).all()
# 使用SQLAlchemy的in_方法
notes = await Note.objects.filter(Note.columns.id.in_([1, 2, 3])).all()
注意区分Note.columns
(SQLAlchemy表列)和Note.fields
(ORM字段)的不同用途。
3. 结果限制 - limit()和offset()
# 限制返回1条记录
await Note.objects.limit(1).all()
# 跳过第一条记录
await Note.objects.offset(1).all()
# 组合使用:获取按ID排序后的第二条记录
await Note.objects.order_by("id").limit(1).offset(1).all()
4. 结果排序 - order_by()
# 按文本升序、ID降序排列
notes = await Note.objects.order_by("text", "-id").all()
返回结果的方法详解
1. 获取全部结果 - all()
# 获取所有笔记
notes = await Note.objects.all()
2. 创建记录 - create()和bulk_create()
# 创建单条记录
await Note.objects.create(text="Buy groceries", completed=False)
# 批量创建记录
await Product.objects.bulk_create([
{"data": {"foo": 123}, "value": 123.456},
{"data": {"foo": 456}, "value": 456.789}
])
3. 删除记录 - delete()
# 删除符合条件的记录
await Note.objects.filter(completed=True).delete()
# 删除单条记录
note = await Note.objects.first()
await note.delete()
# 清空表(谨慎使用)
await Note.objects.delete()
4. 存在性检查 - exists()
# 检查是否存在已完成笔记
has_completed = await Note.objects.filter(completed=True).exists()
5. 获取单条记录 - first()和get()
# 获取第一条记录(可能返回None)
note = await Note.objects.first()
# 通过主键获取记录
note = await Note.objects.get(pk=2)
# 获取特定ID的记录(严格匹配一条)
try:
note = await Note.objects.get(id=1)
except orm.NoMatch:
print("记录不存在")
except orm.MultipleMatches:
print("找到多条匹配记录")
6. 更新记录 - update()
# 批量更新
await Note.objects.filter(completed=True).update(completed=False)
# 更新单条记录
note = await Note.objects.first()
await note.update(completed=True)
# 全表更新(谨慎使用)
await Note.objects.update(completed=False)
高级便利方法
1. 获取或创建 - get_or_create()
# 获取或创建记录
note, created = await Note.objects.get_or_create(
text="Car wash",
defaults={"completed": False}
)
2. 更新或创建 - update_or_create()
# 更新或创建记录
note, created = await Note.objects.update_or_create(
text="Car wash",
defaults={"completed": True}
)
最佳实践与注意事项
- 异常处理:使用
get()
方法时务必处理NoMatch
和MultipleMatches
异常 - 链式调用:合理组合查询方法,如先过滤再排序最后分页
- 批量操作:优先使用
bulk_create()
和批量update()
提高性能 - 事务管理:重要操作应在事务中执行,确保数据一致性
- 索引优化:频繁查询的字段应考虑添加数据库索引
总结
Encode ORM提供了丰富而灵活的查询接口,从简单的CRUD操作到复杂的查询组合都能轻松应对。掌握这些查询方法后,开发者可以高效地构建数据访问层,同时保持代码的简洁性和可维护性。在实际项目中,应根据具体场景选择最合适的查询方式,并注意性能优化和数据一致性保障。
orm An async ORM. 🗃 项目地址: https://gitcode.com/gh_mirrors/orm/orm
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考