1
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' 值由所有相关订单的数量决定,但仍处于活动状态。

编辑:更准确地说,我只需要对活动订单的数量求和。

4

2 回答 2

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

sum = queryset['order__quantity__sum']
于 2013-03-21T04:06:55.017 回答
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
于 2013-03-21T07:18:38.020 回答