代码之家  ›  专栏  ›  技术社区  ›  bur

每次从模板调用方法都会查询数据库吗?

  •  0
  • bur  · 技术社区  · 1 月前

    假设你在模型中有以下方法:

        def get_images(self):
            return ReleaseImage.objects.filter(release=self.id)
    

    你从这样的模板中调用它:

    {% if release.get_images %}{{ MEDIA_URL }}{{ release.get_images.first }}{% endif %}
    

    数据库是否会被查询两次,还是有一些幕后优化可以防止这种情况?若非如此,其效率可能极低。

    1 回复  |  直到 1 月前
        1
  •  1
  •   willeM_ Van Onsem    1 月前

    它在这里查询了两次,是的。但我们可以用 {% with … %} template tag [Django-doc] :

    {% with images=release.get_images %}
    {% if images %}{{ MEDIA_URL }}{{ images.0 }}{% endif %}
    {% endwith %}