掌握 ORM 核心查询能力
一、QuerySet 基础特性
1. 延迟执行机制
# 查询不会立即执行
qs = Product.objects.filter(price__gt=100)
# 实际执行时机:
print(qs) # 第一次访问数据
for p in qs: # 迭代时
list(qs) # 转换为列表时
2. 链式调用
# 支持无限链式组合
Product.objects
.filter(category='Electronics')
.exclude(stock=0)
.order_by('-price')
.select_related('manufacturer')
3. 缓存机制
qs = Product.objects.all()
list(qs) # 第一次查询数据库
list(qs) # 使用缓存结果
二、数据检索方法
1. 基础检索
| 方法 | 功能 | 示例 |
|---|---|---|
| all() | 获取所有记录 | Product.objects.all() |
| get() | 获取单条记录 | .get(id=1) |
| first() | 获取第一条 | .order_by('price').first() |
| last() | 获取最后一条 | .order_by('created_at').last() |
| exists() | 检查是否存在 | .filter(price__gt=1000).exists() |
all() 方法
特点:
永远返回 QuerySet 对象
空表时返回空 QuerySet
不会报错
# 当表中有数据时
products = Product.objects.all()
print(len(products)) # 输出记录数,如 100
# 当表中无数据时
empty_set = Product.objects.all()
print(len(empty_set)) # 输出 0
print(empty_set) # 输出 <QuerySet []>
get() 方法
特点:
期望返回单个对象
无匹配时抛出 .DoesNotExist 异常
多个匹配时抛出 MultipleObjectsReturned 异常
需要异常处理
try:
# 存在时返回对象
product = Product.objects.get(id=1)
# 不存在时抛出异常
missing = Product.objects.get(id=9999) # 抛出 Product.DoesNotExist
except Product.DoesNotExist:
print("产品不存在")
except Product.MultipleObjectsReturned:
print("找到多个匹配项")
first() 方法
特点:
返回模型实例或 None
常与 order_by() 配合使用
不会报错
# 存在时返回第一个对象
first_product = Product
© 版权声明
文章版权归作者所有,未经允许请勿转载。如内容涉嫌侵权,请在本页底部进入<联系我们>进行举报投诉!
THE END




![[干货]小米手机福利——不止是双开微信,QQ,游戏….. - 宋马](https://pic.songma.com/blogimg/20250627/0d17111ef6dc4bdaa242c7d46826a1aa.jpg)















暂无评论内容