Django用相关表上的条件注释总和
Posted
技术标签:
【中文标题】Django用相关表上的条件注释总和【英文标题】:Django annotate sum with a condition on a related table 【发布时间】:2013-03-21 03:45:37 【问题描述】: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' 值由所有相关但处于活动状态的订单的数量决定。
编辑: 更准确地说,我只需要对活跃订单的数量求和。
【问题讨论】:
【参考方案1】:queryset = Inventory.objects.filter(product=product,
order__active=True).aggregate(
Sum('order__quantity'))
sum = queryset['order__quantity__sum']
【讨论】:
这会过滤订单仅处于活动状态的库存。也许我的问题不清楚。对此感到抱歉。我正在寻找的是所有“order_quantity”活动订单的总和。就像在总和中嵌套一个过滤器一样。 这就是您所需要的,对吧?I need to get queryset of inventory that has annotated 'used' value. 'used' value is determined by quantity of all related orders but are active.
好的更新,sum of all 'order_quantity' for orders that are active
我需要对总和进行注释。在原始 SQL 中,它可能是这样的:SUM(CASE WHEN "order_invoiceline"."active" = 1 THEN "orders_invoiceline"."quantity" ELSE 0 END)
【参考方案2】:
我用原始 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
【讨论】:
以上是关于Django用相关表上的条件注释总和的主要内容,如果未能解决你的问题,请参考以下文章
Laravel HasManyThrough 与相关表上的 Where 条件的关系
在 Django 中有一种方法可以聚合与相关对象上的条件的关系