在sqlite中使用django prefetch_related

时间:2022-06-01 20:26:06

I have a model which is related with other model.

我有一个与其他模型相关的模型。

class Foo(...)
 ...

class Bar(...)
 foo = models.ForeignKey(Foo, related_name('bars'))

I need to load all related Bars for many Foos so I use prefetch_related.

我需要为许多Foos加载所有相关的Bars,所以我使用prefetch_related。

Foo.objects.filter(...).prefetch_related('bars')

In debug_toolbar I see additional query which takes Bars for all foos, but there are also queries which takes Bars for every single Foo.

在debug_toolbar中,我看到了另外的查询,其中包含了所有foos的Bars,但是也有查询为每个Foo采用Bars。

Doesn't prefetch_related work in sqlite? Or am I doing something wrong?

在sqlite中prefetch_related不工作吗?或者我做错了什么?

I iterate through all Foos in template, but I think this does not matter.

我在模板中遍历所有Foos,但我认为这无关紧要。

1 个解决方案

#1


0  

Ok, the problem was in my code. I used latest() method in my manager which executed another query.

好的,问题出在我的代码中。我在我的经理中使用了latest()方法,执行了另一个查询。

#1


0  

Ok, the problem was in my code. I used latest() method in my manager which executed another query.

好的,问题出在我的代码中。我在我的经理中使用了latest()方法,执行了另一个查询。