I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:
queryset = Modelclass.objects.filter(somekey=foo)
In my template I would like to do
{% for object in data.somekey_set.FILTER %}
but I just can't seem to find out how to write FILTER.
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.
To filter a Python Django query with a list of values, we can use the filter method with in . to search Blog entries with pk set to 1,4 or 7 by calling Blog. objects. filter with the pk_in argument set to [1, 4, 7] .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With