In the queryset, I want to get the average of what subquery returns and then group by 'store_id' and 'avg_sales'. However, when I used the following queries:
subquery = StoreStatistics.objects.filter(
store=OuterRef("store_id"),
products__in=products, # list of ids
created_date__gte='2023-01-01',
).annotate(
month=TruncMonth("created_date")
).values(
"month", "store"
).annotate(
avg_sales_per_month=Avg("quantity")
)
queryset = Company.objects.filter(
company_id=company_id
).annotate(
avg_sales=Subquery(subquery.aggregate(Avg("avg_sales_per_month")))
).values(
"store_id", "avg_sales"
)
I got the following error:
This queryset contains a reference to an outer query and may only be used in a subquery.
Can anyone tell where am I making a mistake?