【发布时间】:2012-10-14 15:36:46
【问题描述】:
我有一个简单的问题。
在我的模板文件中,我有两次相同的变量{{ category.photo_set.count }}。
例如:
<div class="galleries">
<div class="row">
{% for category in categories %}
<div class="five columns{% cycle " alpha" "" " omega" %}">
<div class="image"><a href="{% url gallery.views.category category.slug %}"><img src="{{ MEDIA_URL }}{{ category.image }}" alt="" /></a></div>
<h4>{{ category.name }}</h4>
<p>Ilość zdjęć: {{ category.photo_set.count }}</p>
{% if category.photo_set.count > 0 %}<a class="button" href="{% url gallery.views.category category.slug %}">zobacz</a>{% endif %}
</div>
{% endfor %}
</div>
</div>
我注意到这段代码对数据库生成了两个完全相同的查询。
30 Query SELECT COUNT(*) FROM `gallery_photo` WHERE `gallery_photo`.`category_id` = 1
30 Query SELECT COUNT(*) FROM `gallery_photo` WHERE `gallery_photo`.`category_id` = 1
如何防止这种情况发生?
【问题讨论】:
标签: sql django model django-templates