Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: check for empty query set

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.

like image 411
user984003 Avatar asked Jul 02 '13 20:07

user984003


People also ask

How do I find the length of a Queryset?

If the QuerySet only exists to count the amount of rows, use count(). If the QuerySet is used elsewhere, i.e. in a loop, use len() or |length. Using count() here would issue another SELECT-query to count the rows, while len() simply counts the amount of cached results in the QuerySet.


1 Answers

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

like image 187
Thales Ceolin Avatar answered Oct 02 '22 13:10

Thales Ceolin