[Answered ]-How to get the sum of transactions per month in django

1👍

You can make use of the Trunc database function

Give this a try

from django.db.models import Sum
from django.db.models.functions import TruncMonth

Transaction.objects.annotate(month=TruncMonth("trans_date"))
    .values("month")
    .annotate(sum=Sum("trans_amount"))

The reslut will look like

[
    {
        "month": "2022-04-01T00:00:00Z",
        "sum": 10.0
    },
    {
        "month": "2022-05-01T00:00:00Z",
        "sum": 20.0
    }
]

Leave a comment