考虑两种模型:
class School(models.Model):
name = TextField()
class Student(models.Model):
school = ForeignKey(School
related_name=students
)
firstname = TextField()
以及查询:
School.objects.filter(Q(name="oldschool") & Q(
Q(students__firstname="hello") | Q(students__firstname="testname")
))
我检索学校。但是,显然执行了连接/子查询,但我没有获取学生信息。我还希望获得“设置了名字”的学生信息。
我可以让 django orm 实际上填充 Students_set,这样我以后就不必进行多次查找吗? (必须遍历学校并检查每个学校)。
.prefetch_related(…)
[Django-doc]:
from django.db.models import Prefetch
schools = School.objects.filter(
Q(students__firstname='hello') | Q(students__firstname='testname'),
name='oldschool',
).prefetch_related(
Prefetch(
'students',
Student.objects.filter(Q(firstname='hello') | Q(firstname='testname')),
)
)
for school in schools:
for student in school.students.all():
print(student)
这将使 one 对 all
Student
进行额外查询,从而对 all School
进行查询,因此有两个查询。这样做是为了减少从数据库到 Django/Python 层的带宽。
但是,如果只有一所学校,从
Student
视图查询更有意义:
Student.objects.filter(
Q(firstname='hello') | Q(firstname='testname'), school__name='oldschool'
)
我们还可以包含
School
数据,但这可能不是一个好主意:
Student.objects.filter(
Q(firstname='hello') | Q(firstname='testname'), school__name='oldschool'
).select_related('school')