[英]Django - using count in template
我有一個簡單的問題。
在我的模板文件中,我有兩次相同的變量{{ 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
我該如何防止這種情況?
這是with
模板標記的一個很好的用例: https : //docs.djangoproject.com/en/dev/ref/templates/builtins/#with
你只想用塊包裝
{% with photo_count=category.photo_set.count %}
...
{{photo_count}}
...
{% endwith %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.