Imagine this simple model:
class Expense(models.Model):
price = models.DecimalField(decimal_places=2, max_digits=6)
description = models.CharField(max_length=300)
category = models.CharField(choices=ExpenseCategory.choices, max_length=20)
created_at = models.DateField()
I'm trying to get the monthly average of price for each category in the current year. My general thought was to do something like:
sub = (
Expense.objects.filter(created_at__year=date.today().year)
.annotate(month=TruncMonth("created_at"))
.values("month", "category")
.annotate(total=Sum("price"))
.order_by("month")
)
qs = Expense.objects.values("category").annotate(avg=Avg(Subquery(sub.values("total"))))
I'm basically trying to:
- Truncate the months of
created_at - Group by
categoryandmonth - Sum the
prices - Aggregate the
pricesfor eachcategory
It works just fine if I do like:
for category in categories:
sub.filter(category=category).aggregate(avg=Avg("total"))