Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the size of a collection within a Django template?

People also ask

How do I get QuerySet size in Django?

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.

What does the built in Django template filter length do?

Returns the length of a list or string Returns the length of a string but not the length of a list Returns the length of a list but not the length of a string Returns the number of characters produced by the template up to this point Returns the number of words in a string 6.

What is Forloop counter in Django?

Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.

What does {{ NAME }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% else %}
    No athletes.
{% endif %}

If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

{% for athlete in athlete_list %}
  ...
{% empty %}
  No athletes
{% endfor %}

Useful when the something that you want to do involves special treatment for lists that might be empty.


A list is considered to be False if it has no elements, so you can do something like this:

{% if mylist %}
    <p>I have a list!</p>
{% else %}
    <p>I don't have a list!</p>
{% endif %}

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count


You can try with:

{% if theList.object_list.count > 0 %}
    blah, blah...
{% else %}
    blah, blah....
{% endif %} 

Collection.count no bracket

{% if request.user.is_authenticated %}
{{wishlists.count}}
{% else %}0{% endif %}

I need the collection length to decide whether I should render table <thead></thead>

but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop afterward.

I got to use {% if forloop.first %} {% endif %} to overcome:

<table>
    {% for record in service_list %}
        {% if forloop.first %}
            <thead>
            <tr>
                <th>日期</th>
            </tr>
            </thead>
        {% endif %}
        <tbody>
        <tr>
            <td>{{ record.date }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>