Menu Close

How to perform query filtering in Python Django templates?

Sometimes, we want to perform query filtering in Python Django templates.

In this article, we’ll look at how to perform query filtering in Python Django templates.

How to perform query filtering in Python Django templates?

To perform query filtering in Python Django templates, we can create a template tag that calls filter.

For instance, we write

@register.filter
def in_category(things, category):
    return things.filter(category=category)

to create the in_category tag function that calls things.filter to filter by category.

Then we write

{% for category in categories %}
  {% for thing in things|in_category:category %}
    {{ thing }}
  {% endfor %}
{% endfor %}

in our template to use the in_category tag with the category as the value of the category parameter.

Conclusion

To perform query filtering in Python Django templates, we can create a template tag that calls filter.

Posted in Python, Python Answers