[Answered ]-Sum numbers and group them by the given month, is there a 'best practice'?

1👍

Try this:

Expense.objects.filter(pom='OUT')\
    .values('when__year', 'when__month')\
    .annotate(total_amount=Sum('amount'))\
    .order_by('-when__year','-when__month')

I included the year, otherwise it will add total_amount of next years months to this years months. Remove the - if you need an ascending order.

This will yield a result like:

<QuerySet [
    {'when__year': 2022, 'when__month':9, 'total_amount': 16000.0}, 
    {'when__year': 2022, 'when__month':8, 'total_amount': 15000.0}
]>

Edit:

Expense.objects.filter(pom='OUT')\
    .values(
        year=models.F('when__year'), 
        month=models.F('when__month')
    ).annotate(total_amount=Sum('amount'))\
    .order_by('-year','-month')

This will yield:

<QuerySet [
    {'year': 2022, 'month':9, 'total_amount': 16000.0}, 
    {'year': 2022, 'month':8, 'total_amount': 15000.0}
]>

Leave a comment