Jbwz
Jbwz

Reputation: 305

How to filter objects from template?

I have 2 models Category and Spending where Category is one of the Spending fields.

User can create custom categories and add spending on the webpage.

The question is, how to filter spendings by categories in Template?

I have:

{% for category in categories %}
    {% for spending in spendings %} 'I want this FOR have only spendings from this category.'

I know how to filter objects with Object.objects.filter() but I am not sure it applies here, because categories are dynamic here

Upvotes: 1

Views: 333

Answers (2)

Astik Anand
Astik Anand

Reputation: 13047

You can do this way.

{% for category in categories %}
     {% for spending in category.spending_set.all %}
         {{spending}}
     {% endfor %}
{% endfor %}

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599628

Use the reverse relation. You haven't shown your models, but presumably there is a foreign key from Spending to Category. If so:

{% for spending in category.spending_set.all %}

Upvotes: 1

Related Questions