prefetch_related为多个级别 [英] prefetch_related for multiple Levels

查看:193
本文介绍了prefetch_related为多个级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的模型看起来像:

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)

我想获取发布者我做 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')`

我的问题是:


  1. 有没有办法使用 select_related
    进行预取,我必须使用 prefetch_related

  2. 有没有办法预取
    page_set ?这不起作用:

  1. Is there a way to do this prefetching using select_related or must I use prefetch_related?
  2. Is there a way to prefetch the page_set? This does not work:

Publisher.objects.all()。prefetch_related('book_set','book_set_page_set ')

推荐答案


  1. 不,你不能使用 select_related 为反向关系。 select_related 执行SQL连接,因此主要查询器中的单个记录需要在相关表中引用一个( ForeignKey OneToOne 字段)。 prefetch_related 实际上完全单独的第二个查询,缓存结果,然后将它加入到python中的查询中。因此,需要 ManyToMany 或反向 ForeignKey 字段。

  1. 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 or OneToOne 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 for ManyToMany or reverse ForeignKey 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆