from django.db.models import Sum, F, FloatField
from django.db.models.functions import ExtractMonth
output = (
Order.objects
.annotate(
month=ExtractMonth("created")
)
.values("month")
.annotate(
count=Sum("products__quantity"),
total=Sum(
F("products__quantity") * F("products__product__price"),
output_field=FloatField()
)
)
.order_by("month")
)