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 models.py
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(self.date)
class Category(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length=150, blank=True)
def __str__(self):
return self.name
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
<ul>
{% for category in object_list %}
<h3> {{ category.name }} </h3>
<ul>
{% for item in category.transaction_set.filter(date__date__year = current_year, date__date__month = current_month) %}
<p> {{ item.description }} - {{ item.date }} {{ item.sum }}</p>
{% endfor %}
</ul>
{% endfor %}
</ul>
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 views.py 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!