Django _set.filter in template

Hi! This has maybe been up before, but I’m unsure what to search for.
I have this project where I’m trying to make an site for keeping statistics for my own economy.
This is my

class Transaction(models.Model):
    date = models.ForeignKey('Date', on_delete= CASCADE)
    sum = models.DecimalField(max_digits=9, decimal_places=2)
    account = models.CharField(max_length=11, default='990310-4439')
    description = models.CharField(max_length= 100)
    category = models.ForeignKey('Category', on_delete= CASCADE)
    tags = models.ManyToManyField('Tag', blank=True)

    class Meta:
        ordering = ["date"]

    def __str__(self):
        return self.description

class Date(models.Model):
    date = models.DateField('Date')

    def __str__(self):
        return str(

class Category(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(max_length=150, blank=True)

    def __str__(self):

    class Meta:
        verbose_name_plural = 'Categories'

I want to have an template that shows the current months transactions, listed by category. My first thought was to filter in the template

{% for category in object_list %}
    <h3> {{ }} </h3>
    {% for item in category.transaction_set.filter(date__date__year = current_year, date__date__month = current_month) %}
        <p> {{ item.description }} - {{ }} {{ item.sum }}</p>
    {% endfor %}
{% endfor %}

But after some research i realized that I cant filter in the template.
From what I understood, the easiest way is to filter in the and return a filtered queryset. But if I try to filter with the following

Category.objects.filter(transaction__date__date__year = year, transactions__date__date__month = month) 

I get a queryset with a category object for every transaction. I want an queryset with all the categories. And from each category I want to get every transactions for that year and month.

My question is, what is the best approach for solving my problem?
Thanks in advance!

This appears to be a case where it’s going to be helpful to “turn your query inside-out” as I like to think of it.

What you want to look for are all the transactions matching your criteria - and then pick up the categories for them along the way.

e.g. Transactions.objects.filter(...).order_by('category__name', 'date').select_related(category)

Or, if you want “N” distinct and separate lists, then that will require two queries. You can select all your categories, and then for each category, you can refer to .transaction_set.filter(...) to get the transactions for that category - but that’s an n+1 query situation that you generally want to avoid.