如何在Django查询中使用group by获得Sum

如何在Django查询中使用group by获得Sum,django,django-models,Django,Django Models,我正试图通过group by product_id获取我的数量之和,但它返回多条记录 我正在研究Django,并试图通过so获得与小组的总和。我尝试使用注释和值 productinventory_ds = ( ProductInventory.objects.filter(product_id=product_id) .values("product_id") .annotate(

我正试图通过group by product_id获取我的数量之和,但它返回多条记录

我正在研究Django,并试图通过so获得与小组的总和。我尝试使用注释和值

productinventory_ds = (
                ProductInventory.objects.filter(product_id=product_id)
                .values("product_id")
                .annotate(
                    instock_quantity_s=Sum("instock_quantity"),
                    delivered_quantity_s=Sum("delivered_quantity"),
                )
            )

但不是给出一个产品id和所有数量的总和。此查询返回具有相同产品id的多个结果。

您应该添加一个
.order\u by(..)
以强制分组,如:

productinventory_ds = ProductInventory.objects.filter(
    product_id=product_id
).values('product_id').annotate(
    instock_quantity_s=Sum('instock_quantity'),
    delivered_quantity_s=Sum('delivered_quantity')
).order_by('product_id')
这将返回一个字典,其中包含两个项,分别为键
'instock\u quantity\u s'
'delivered\u quantity\u s'

productinventory_ds = ProductInventory.objects.filter(
    product_id=product_id
).aggregate(
    instock_quantity_s=Sum('instock_quantity'),
    delivered_quantity_s=Sum('delivered_quantity')
)