I have simple question.
In my template file i have the same variable {{ category.photo_set.count }} twice.
For example:
<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>
And i noticed that this code generates two exactly the same queries to the database.
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
How can i prevent this?
This is a great use case for the
withtemplate tag: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#withYou’ll just want to wrap the block with