admin管理员组文章数量:1316645
Say you have the following method in a model:
def get_images(self):
return ReleaseImage.objects.filter(release=self.id)
And you call it from a template like so:
{% if release.get_images %}{{ MEDIA_URL }}{{ release.get_images.first }}{% endif %}
Does the database get queried twice, or is there some behind-the-scenes optimization that prevents this? It might be highly inefficient if not.
Say you have the following method in a model:
def get_images(self):
return ReleaseImage.objects.filter(release=self.id)
And you call it from a template like so:
{% if release.get_images %}{{ MEDIA_URL }}{{ release.get_images.first }}{% endif %}
Does the database get queried twice, or is there some behind-the-scenes optimization that prevents this? It might be highly inefficient if not.
Share Improve this question asked Jan 31 at 21:06 burbur 7686 silver badges22 bronze badges1 Answer
Reset to default 1It queries twice here, yes. But we can optimize it with a {% with … %}
template tag [Django-doc]:
{% with images=release.get_images %}
{% if images %}{{ MEDIA_URL }}{{ images.0 }}{% endif %}
{% endwith %}
As with (most) Django template tags, you can not add spaces around the equal sign (=
).
本文标签: djangoDoes calling a method from template query the database each timeStack Overflow
版权声明:本文标题:django - Does calling a method from template query the database each time? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741894652a2403506.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论