Categories
Python Answers

How to perform query filtering in Python Django templates?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *