Django template: check for empty query set

django, django-templates

Solution

Have a look at the {% empty %} tag. Example from the documentation

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>

Link: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for-empty

If you are interested in a table, or some kind of heading if there are results, add the `forloop.first`:

{% for athlete in athlete_list %} {% if forloop.first %} Athlete Name: {% endif %}

- {{ athlete.name }}

{% empty %}

- Sorry, no athletes in this list.

{% endfor %}

Problem

Is there a way to check for an empty query set in the Django template? In the example below, I only want the NOTES header to be displayed if there are notes. If I put an {% empty %} inside the "for" then it does display whatever is inside the empty tag, so it knows it's empty. I'm hoping for something that does not involve running the query twice. ``` {% if notes - want something here that works %} NOTES: {% for note in notes %} {{note.text}} {% endfor %} {% endif %} ``` Clarification: the above example "if notes" does not work - it still displays the header even with an empty query set. Here's a simplified version of the view ``` sql = "select * from app_notes, app_trips where" notes = trip_notes.objects.raw(sql,(user_id,)) return render_to_response(template, {"notes":notes},context_instance=RequestContext(request)) ``` Edit: the view select selects from multiple tables.

Original source