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)

注釈付きの「使用済み」値を持つ在庫のクエリセットを取得する必要があります。「使用済み」の値は、関連するすべての注文の数量によって決定されますが、アクティブです。

編集:より正確に言うと、アクティブな注文のみの数量を合計する必要があります。

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 に答える