Django,在反向相关管理器上重用select_related / prefetch_related?

时间:2017-01-27 07:17:24

标签: django django-models

我可以看到select_related减少查询次数。

但是,当我多次运行相同的查询时,我希望看到第一个查询被重用,但它不在以下设置中。

class Foo(models.Model):

    pass


class Bar(models.Model):

    foo = models.ForeignKey(Foo, related_name='bars')
    blog = models.ForeignKey('blg.blog')



foo = Foo.objects.create()
bar1 = Bar.objects.create(foo=foo)
bar2 = Bar.objects.create(foo=foo)

foo.bars.select_related('blog')
foo.bars.select_related('blog') # <= here, it runs the query again 

如何告诉django在第二次运行时重用第一个数据库查询?

1 个答案:

答案 0 :(得分:0)

select_related并不意味着任何缓存,只是执行JOIN,因此您不需要新的数据库查询来获取返回对象的相关对象。

for bar in foo.bars.all():
    bar.blog  # A query to fetch the blog object is made for each bar object in the loop.

for bar in foo.bars.select_related('blog'):
    bar.blog  # No query is made, the blog object has already been fetched.

如果您不想进行多个数据库查询,只需将查询集存储到变量中并重用相同的查询集,例如:

bars = foo.bars.select_related('blog')

for bar in bars:  # The first loop executes the DB query and caches its result
    # Do something

for bar in bars:  # The second loop uses the cached results
    # Do something else