Reputation: 104
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?
Upvotes: 0
Views: 797
Reputation: 9890
This is a great use case for the with
template tag: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#with
You'll just want to wrap the block with
{% with photo_count=category.photo_set.count %}
...
{{photo_count}}
...
{% endwith %}
Upvotes: 2