I've been trying to rework a query and I can't figure out the solution. Here is the setup (oversimplified):
An object OrderLine with a quantity and a product, and the product itself with a stock
class Product(models.Model):
inventory_quantity = models.IntegerField()
class OrderLine(models.Model):
product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField()
What I want to do is annotate Product to know the predicted inventory and use it later in the code. I had this code that was working in Django 2:
subquery_projected_product = OrderLine.filter(
product_id__in=OuterRef('id')
).annotate(
qty=ExpressionWrapper(
F('product__inventory_quantity') -
OrderLine.sum_quantity_sql(),
output_field=IntegerField()
)
).values('qty')
products_queryset = Product.objects.all().
annotate(
nb_projected=Subquery(
subquery_projected_product,
output_field=IntegerField()
)
)
But after Django switch to version 3 I ran into this: https://code.djangoproject.com/ticket/31135.
If I understand correctly, this is not the correct way to do the request and it`s not supported anymore.
So to put it simple, how can I, for each product, annotate the sum of quantity of related orderlines ?
Thanks and have a good day.