Django用相关表上的条件注释sum

时间:2013-03-21 03:45:37

标签: sql django orm annotate

class Inventory(models.Model):
    ...
    product = models.ForeignKey('Product')
    quantity = models.IntegerField(default=0)


class Order(models.Model):
    ...
    quantity = models.IntegerField()
    inventory = models.ForeignKey('Inventory')
    active = models.BooleanField(default=True)

# Not considering the orders that are not active
queryset = Inventory.objects.annotate(
    used=Sum('order__quantity')
).filter(product=product)

我需要获取已注释“已使用”值的库存的查询集。 'used'值由所有相关订单的数量决定,但是有效。

修改: 更确切地说,我需要只计算有效订单的数量。

2 个答案:

答案 0 :(得分:1)

queryset = Inventory.objects.filter(product=product, 
    order__active=True).aggregate(
    Sum('order__quantity'))

sum = queryset['order__quantity__sum']

答案 1 :(得分:1)

我用原始SQL找出了答案:

SELECT "products_inventory"."id", "products_inventory"."product_id", "products_inventory"."quantity",
SUM(CASE WHEN "orders_order"."active" = True THEN "orders_order"."quantity" ELSE 0 END)
AS "used" FROM "products_inventory"
LEFT OUTER JOIN "orders_order" ON ("products_inventory"."id" = "orders_order"."inventory_id")
WHERE "products_inventory"."product_id" = id_of_product
GROUP BY "products_inventory"."id", "products_inventory"."product_id", "products_inventory"."quantity",
ORDER BY "products_inventory"."id" ASC