prefetch_related为多个级别 [英] prefetch_related for multiple Levels
问题描述
如果我的模型看起来像:
If my Models look like:
class Publisher(models.Model):
pass
class Book(models.Model):
publisher = models.ForeignKey(Publisher)
class Page(models.Model):
book = models.ForeignKey(Book)
我想获取发布者$的查询c $ c>我做
Publisher.object.all()
。
如果然后想要确保预取我可以做:
and I would like to get the queryset for Publisher
I do Publisher.object.all()
.
If then want to make sure to prefetch I can do:
Publisher.objects.all().prefetch_related('book_set')`
我的问题是:
- 有没有办法使用
select_related
或
进行预取,我必须使用prefetch_related
? - 有没有办法预取
page_set
?这不起作用:
- Is there a way to do this prefetching using
select_related
or must I useprefetch_related
? - Is there a way to prefetch the
page_set
? This does not work:
Publisher.objects.all()。prefetch_related('book_set','book_set_page_set ')
推荐答案
-
不,你不能使用
select_related
为反向关系。select_related
执行SQL连接,因此主要查询器中的单个记录需要在相关表中引用一个(ForeignKey
或OneToOne
字段)。prefetch_related
实际上完全单独的第二个查询,缓存结果,然后将它加入到python中的查询中。因此,需要ManyToMany
或反向ForeignKey
字段。
No, you cannot use
select_related
for a reverse relation.select_related
does a SQL join, so a single record in the main queryset needs to reference exactly one in the related table (ForeignKey
orOneToOne
fields).prefetch_related
actually does a totally separate second query, caches the results, then "joins" it into the queryset in python. So it is needed forManyToMany
or reverseForeignKey
fields.
你尝试过两个下划线来做多级预取吗?像这样: Publisher.objects.all()。prefetch_related('book_set','book_set__page_set')
Have you tried two underscores to do the multi level prefetches? Like this: Publisher.objects.all().prefetch_related('book_set', 'book_set__page_set')
这篇关于prefetch_related为多个级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!