I'm making an aggregate report of stores, categories and customers for an ecommerce. Basically, I'm trying to achieve what this function does:
from django.db.models import ExpressionWrapper, DecimalField, F, Sum
from .models import Order
def get_report_data(stores, categories, customers):
result = []
for store in stores:
for category in categories:
for customer in customers:
total = Order.objects.filter(
store=store,
orderitem__product__category=category,
customer=customer,
).aggregate(
total=Sum(
ExpressionWrapper(
F("orderitem__product__price") * F("orderitem__quantity"),
output_field=DecimalField(),
)
)
)["total"]
result.append([store, customer, category, total])
return result
Obviously, this is efficiently poor and I'm trying to turn this function into a query. I've tried the following, but I know I'm missing the mark by A LOT.
total = (
Order.objects.filter(
store__in=stores,
customer__in=customers,
orderitem__product__category__in=categories,
)
.values("store", "orderitem__product__category")
.annotate(
total=Sum(
ExpressionWrapper(
F("orderitem__product__price") * F("orderitem__quantity"),
output_field=DecimalField(),
)
)
)
)
How should I proceed?
Thank you very much!