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 4, 2020 in Python by kartik
• 37,520 points
12,554 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 4, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How can I do not equal in Django queryset filtering?

Hello @kartik, You can use Q objects for this. They ...READ MORE

answered Nov 17, 2020 in Python by Niroj
• 82,880 points
747 views
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
533 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
667 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, 2020 in Python by Niroj
• 82,880 points
9,057 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, 2020 in Python by Niroj
• 82,880 points
2,334 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, 2020 in Python by Niroj
• 82,880 points
1,486 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, 2020 in Python by Niroj
• 82,880 points
33,979 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, 2020 in Python by Niroj
• 82,880 points
4,599 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP