Getting the Size of a Collection in a Django Template

Django’s template language provides a rich set of features for displaying data from your models and controllers. However, it does not have a direct way to get the length or size of a collection. In this post, we’ll explore a few different approaches to getting the size of a list, set, or other collection within a Django template.

Use the |length Filter

One easy way to get the size of a list or array is to use Django’s |length filter. For example:

{% my_list|length %}

This will display the number of items in my_list. Some key points about the |length filter:

  • It works on lists, tuples, dicts, and other sequence-like objects
  • For a dict, it returns the number of keys
  • For a queryset, it performs a COUNT(*) to get the number of matching rows

The |length filter provides a simple way to get the size of things like:

  • Context variables passed from the view
  • Results from quersets
  • Query dict objects

Define a Custom Template Tag

Another approach is to write your own simple template tag to get the size. First we’d register our custom template library in myapp/templatetags/

from django import template

register = template.Library()

def collection_size(collection):
    return len(collection)

Then in our Django template:

{% load my_extras %}

{% my_list|collection_size %}

This keeps the display logic out of the view and makes things more reusable. Some key advantages:

  • Can be designed specifically for template usage
  • Works for cases where |length doesn’t apply
  • More descriptive name

Use a Template Variable Assignment

We can also get the size in the template using a variable assignment. This stores the size in a variable for repeated use:

{% with my_list|length as my_list_size %}
    Size: {{ my_list_size }}
{% endwith %}

This generates a little more code, but avoids calling the filter multiple times. This technique also works with custom filters and template tags.

Some trade-offs to consider – variable assignments can add complexity, but are useful for reusable values.


To recap, Django templates provide several options for getting collection sizes, including:

  • The built-in |length filter for basic sequence-like objects
  • CustomTemplate filters for more targeted sizes
  • Template variables to store the size as needed

Choosing the right approach depends on where the data is coming from and how the size will be displayed or used. As templates gain more logic, also consider handling sizes in view methods and exposing them as context variables. Multi-purposeTemplate tags are another handy way to reuse display logic.

Hopefully this gives you some options to tackle displaying collection sizes in Django templates! Let me know if you have any other questions.