django orm 中的select_related
1. 我们基于以下模型来分析select_related的作用。
class Person(models.Model);
name = models.CharField(max_length=30)
age = models.IntegerField()
class Book(models.Model):
person = models.ForeignKey(Person)
title = models.CharField(max_length=50)
pubtime = models.DateField()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
2. 模型结构为:
Book - title
- page
- person -> ForeignKey(Person)
- 1
- 2
- 3
3. 两种查询方式:
A. 不带select_related
book = Book.objects.filter(pk=1) # 需要查询数据库 1
---------------------
result:
book - id
- title
- page
- Person.id
---------------------
n = book.name # 需要查询数据库 2
a = book.age # 需要查询数据库 3
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
*总共向数据库发起三次查询。
B. 带select_related
book = Book.objects.select_related().filter(pk=1) # 需要查询数据库 1
---------------------
result:
book - id
- title
- page
- Person - id
- name
- age
---------------------
n = book.name # 直接从book对象中取
a = book.age # 直接从book对象中取
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
*总共向数据库发起一次查询。
也就是说使用select_related()方法一次性的把Book关联的对象都查询出来放入对象中,再次查询时就不需要再连接数据库,节省了后面查询数据库的次数和时间。
4. depth参数
depth参数可以指定select_related(depth=2)关联的对象的层数,这里就不作详细解释。
5. 指定关键字参数
指定关键字参数可以只查询(join)指定的对象,节省资源。
book = Book.objects.select_related('person').filter(pk=1)
# 假设Person模型中有另外一个外键city,可作如下查询
book = Book.objects.select_related('person__city').filter(pk=1)
- 1
- 2
- 3
- 4
浙公网安备 33010602011771号