How do I perform query filtering in Django templates

Published 2 days ago5 min read4 comments

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

Just add  template tag like this:

def in_category(blog_list, category):
    return blog_list.filter(category=category)

Then I can do this in template:

{% for category in categories %}
  {% for blog in blogs|in_category:category %}
    {{ blog }}
  {% endfor %}
{% endfor %}