I have the following Django models:
class Order(models.Model):
...
org_slug = models.CharField()
class ProductToOrder(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
qty = models.IntegerField()
cost = models.FloatField()
I need to sum Orders that grouped by on org_slug and it must have sum of orders that have only one ProductToOrder and ProductToOrder.qty=1
I'm trying to do it in this way
orders = Order.objects.filter(
some_filter_here
).values('org_slug').annotate(
order_sum=Subquery(Order.objects.filter(
org_slug=OuterRef('org_slug')).annotate(
product_count=Coalesce(Sum('producttoorder__qty'), 1)
).filter(product_count=1).values('org_slug').annotate(
sum=Sum('producttoorder__cost')
).values('sum')[:1]))
But it returns queryset of all orders. For example, if I have 1000 orders and 2 org_slugs, I need to get 2 objects in the query list but it returns 1000. This line where I'm trying to group by queryset in the following Subquery does not work:
.filter(product_count=1).values('org_slug')
I'm tried a lot of different querysets to fix it but it didn't give me any positive result. I see only one way to fix it, I need to create qty field in Order model but I hope, there are other ways to fix it. Can anybody help me with it?
Order
has noProductToOrder
s withqty=1
, or multiple?Order
andAppsOrder
?