Django链prefetch_related和select_related [英] Django chaining prefetch_related and select_related
问题描述
假设我有以下模型
class Foo(models.Model):
...
class Prop(models.Model):
...
class Bar(models.Model):
foo: models.ForeignKey(Foo, related_name='bars', ...)
prop: models.ForeignKey(Prop, ...)
现在我要进行以下查询。
Now I want to make the following query.
foos = Foo.objects.prefetch_related('bars__prop').all()
上面的查询是否进行3次数据库调用或仅进行2次(对于 prop
来自 bar
),因为只有一个 prop
与 bar
Does the above query makes 3 Database calls or only 2 (select_related for prop
from bar
), given that only one prop
is associated with bar
如果需要接听3个电话,是否可以通过对<$ c使用selected_related使其成为2个电话$ c> bar-> prop
If it takes 3 calls then, is there a way to make it 2 calls by using selected_related for bar -> prop
推荐答案
您可以使用 Prefetch
类来指定 prefetch_related()
中使用的查询集,并通过这种方式将其与 select_related()
组合:
You can use the Prefetch
class to specify the queryset that is used in prefetch_related()
and this way combine it with select_related()
:
from django.db.models import Prefetch
bars = Bar.objects.select_related('prop')
foos = Foo.objects.prefetch_related(Prefetch('bars', queryset=bars)).all()
这应该是两个查询,一个用于 Foo
对象,一个用于获取相关的 Bar
对象与 Prop
相同的查询。
Note that this should be two queries, one for the Foo
objects and one for getting the related Bar
objects that are being joined in the same query with Prop
.
这篇关于Django链prefetch_related和select_related的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!