我在项目中遇到这样的查询集:
qs.prefetch_related().other().methods()
是否有必要在不指定任何查找的情况下调用 prefetch_lated()
方法?
最佳答案
Is there a point having such call to
.prefetch_related()
method without specifying any lookup?
不会,或者至少对于“普通”经理来说不会。用户可能创建了 QuerySet
和/或 Manager
的子类,从而稍微改变了行为。
我怀疑这是基于 .select_related(…)
call [Django-doc] 的行为:
In these cases it is possible to call
select_related()
with no arguments. This will follow all non-null foreign keys it can find - nullable foreign keys must be specified. This is not recommended in most cases as it is likely to make the underlying query more complex, and return more data, than is actually needed.
在这种情况下,它将自动包含所有 ForeignKey
(和 OneToOneField
),因此只需选择任何多对一或一对一同一查询中的关系。
作者可能有这样的想法 - 这并不奇怪 - .prefetch_related(…)
[Django-doc] 也是如此。 ,但它确实不。
因此,如果您不向 .prefetch_lated(…)
传递任何参数,它将不会进行任何预取。如果我们只预取任何关系,它也可能会产生大量查询。
如果没有额外的逻辑添加到自定义QuerySet
,.prefetch_lated()
将充当将复制的无操作 QuerySet
,就像 .all()
一样。
关于django - 在不指定查找的情况下调用 prefetch_lated() 有用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76618182/