I started a new project to get a bit back to development. I have a Recipe model, an IngredientGroup model, an Ingredient model, an IngredientDetail model and a Stock model (also a StockGroup model, which is not relevant here). Below are the relevant model definitions:
I use DRF for the API, and I would like to make an endpoint where the recipes are ordered by how many ingredients are missing from stock compared to ingredients. I've tried to make a query, but it works partly, see the below:
There are 2 nested subqueries. The first gets the stock for a current ingredient (same ingredient might be on stock more than once, hence the need to group by ingredient_id and sum on the amount. The next query uses the first subquery to compare the total required (again, grouping on ingredient_id and summing on amount), then annotating the IngredientDetail so it's 1 if total_available < total_required and 0 otherwise.
Up until then, this works, if I manually switch out the OuterRef('pk') I get the expected result.
With some test data (recipe 1: 1 ingredient is missing, recipe 2: 2 ingredients are missing, I get the following output from print(total_required_per_ingredient_subquery, total_required_per_ingredient_subquery.aggregate(Sum('is_missing')))
<QuerySet [{'is_missing': 1}, {'is_missing': 0}, {'is_missing': 0}, {'is_missing': 0}, {'is_missing': 0}, {'is_missing': 0}]> {'is_missing__sum': 1}
<QuerySet [{'is_missing': 1}, {'is_missing': 1}, {'is_missing': 0}, {'is_missing': 0}, {'is_missing': 0}]> {'is_missing__sum': 2}
There's 1 object per ingredient in the recipe.
My question is, how do I properly incorporate the second subquery into the last query to annotate each recipe with the amount of missing ingredients?