How do I perform query filtering in django templates?

0 votes

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.

Jul 3 in Python by kartik
• 19,650 points
72 views

1 answer to this question.

0 votes

Hello @KARTIK,

Just add an extra template tag like this:

@register.filter
def in_category(things, category):
    return things.filter(category=category)

Then you can do:

{% for category in categories %}
  {% for thing in things|in_category:category %}
    {{ thing }}
  {% endfor %}
{% endfor %}

Hope it helps!!
Thank you!!

answered Jul 3 by Niroj
• 41,480 points

Related Questions In Python

0 votes
0 answers

how do i perform XML parsing in python?

can you give me the python code ...READ MORE

Apr 10, 2019 in Python by Waseem
• 4,540 points
71 views
0 votes
0 answers

how do i install django in my system for the project?

can you tell me the procedure for ...READ MORE

May 3, 2019 in Python by Waseem
• 4,540 points
47 views
0 votes
1 answer

How do I get user IP address in django?

Hii Kartik, check uwsgi + django source code and pass static param ...READ MORE

answered Apr 23 in Python by Niroj
• 41,480 points
1,274 views
0 votes
1 answer

How to do a not equal in Django queryset filtering?

Hello @kartik, Your query appears to have a ...READ MORE

answered Jun 26 in Python by Niroj
• 41,480 points
109 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
58 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23 in Python by Niroj
• 41,480 points
40 views
0 votes
1 answer

How do I filter query objects by date range in Django?

Hello @kartik, Use Sample.objects.filter(date__range=["2020-01-01", "2020-01-31"]) Or if you are just ...READ MORE

answered Jun 26 in Python by Niroj
• 41,480 points
189 views
0 votes
1 answer

How do I do a not equal in Django queryset filtering?

Hello @kartik, Try this code below: >>> from myapp.models ...READ MORE

answered Jul 3 in Python by Niroj
• 41,480 points
125 views