[Answered ]-How to aggregate over multiple fields in Django?

1👍

Try this:)

from django.db.models import Sum, Avg

qs = Trade.objects.values('datetime').order_by('datetime').annotate(
    cum_a=Sum('amount'), 
    cum_t=Sum('trades'), 
    avg_p=Avg('price')
)

You iterate like that:

for row in qs:
    print(row["datetime"], row["cum_a"], row["cum_t"], row["avg_p"])

On SQL side you are grouping by datetime and running aggregation for each group.

SELECT "datetime", SUM("amount") AS "cum_a", SUM("trades") AS "cum_t", AVG("price") AS "avg_p"
FROM "Trade"
GROUP BY "datetime"
ORDER BY "datetime"

if you want to group by market too:

qs = Trade.objects.values('datetime', 'market').order_by('datetime', 'market') \
              .annotate(
                  cum_a=Sum('amount'), 
                  cum_t=Sum('trades'), 
                  avg_p=Avg('price')
              )

for row in qs:
    print(row["datetime"], row["market"], row["cum_a"], row["cum_t"], row["avg_p"])

Leave a comment