Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform query filtering in django templates

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.

like image 764
Ber Avatar asked Oct 21 '08 23:10

Ber


People also ask

Can I filter in a Django template?

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.

How can I filter a Django query with a list of values?

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] .


1 Answers

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.

like image 122
Eli Courtwright Avatar answered Sep 17 '22 21:09

Eli Courtwright