Filtering related objects in template

232 views
Skip to first unread message

BigBlogMaker

unread,
Jan 8, 2011, 1:56:40 PM1/8/11
to Django users
Can I filtering of related objects in a template? Explained:
Now I make so

{% for image in product.image_set.all %}
{% if image.image_type.id == 777 %}
<img...................>
{% endif %}
{% endfor %}

And I would like to:

{% for image in product.image_set.all | image_type.id : 777 %}
<img...................>
{% endfor %}

----------------------------------------------------------------------------------
(sorry for my English %))

+shaun

unread,
Jan 8, 2011, 3:05:58 PM1/8/11
to django...@googlegroups.com
From Stackoverflow - How do I perform query filtering in django templates:

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.
Reply all
Reply to author
Forward
0 new messages