How to perform query filtering in Python django templates?

Estimated read time 2 min read

In Django templates, you can perform query filtering using the template language’s built-in filter tag. The filter tag allows you to filter a queryset based on certain conditions.

Here’s an example:

Assuming you have a model called Book with fields title, author, and published_date, you can filter the queryset of Book objects to only include books published after a certain date in your template using the following code:

{% for book in books|filter(published_date__gt=date(2020, 1, 1)) %}
  {{ book.title }}
{% endfor %}

In this example, we are filtering the books queryset to only include books whose published_date is greater than January 1, 2020. The __gt lookup allows us to compare the published_date field with the specified date.

You can also chain multiple filters together, like so:

{% for book in books|filter(published_date__gt=date(2020, 1, 1))|filter(author__icontains='rowling') %}
  {{ book.title }}
{% endfor %}

In this example, we are filtering the books queryset to only include books whose published_date is greater than January 1, 2020, and whose author name contains the string “rowling”. The __icontains lookup allows us to perform a case-insensitive search for the specified string in the author field.

Note that the filter tag only filters the queryset passed to it and does not modify the original queryset. If you want to modify the queryset, you should perform the filtering in your view and pass the filtered queryset to the template context.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply