首页 > 解决方案 > Django 使用 prefetch_related 或 select_related 的有效方法

问题描述

我经常使用prefetch_related&select_related一次性处理嵌套查询。我想让你知道我们可以做更多的事情来让它更快一点。

Foo.objects.prefetch_related('bar')

在我的应用程序中的某些情况下,我只需要特定列(如果Bar模型)。

在下面的方法中使用自定义查询集是否可以prefetch_related提高查询速度?

Foo.objects.prefetch_related(Prefetch('bar',queryset=Bar.objects.all().only('id')))

标签: djangodjango-modelsdjango-rest-frameworkdjango-formsdjango-templates

解决方案


推荐阅读