Django Group_By和SUM查询

时间:2014-11-03 22:00:33

标签: django django-queryset

我想制作一份sumarized库存报告。为了实现这一点,我有这样的模型:

class Inventario(models.Model):
    producto = models.ForeignKey(Producto)
    cantidad = models.DecimalField(default=0,decimal_places=2, max_digits=10)
    ubicacion = models.ForeignKey(Ubicacion, null=True, blank=True)
    def __unicode__(self):
        return self.producto.item

在SQL-RAW中,我会使用正确的JOIN(

)制作类似SELECT producto.nombre as item, sum(cantidad) as cantidad,... FROM Inventario GROUP BY item的内容

我会得到类似的东西:

|Item------- | Cantidad|
|PROD1       | 20      |
|PROD2       | 10      |

而不是

|Item------- | Cantidad|
|PROD1       | 5       |
|PROD1       | 5       |
|PROD1       | 10      |
|PROD2       | 9       |
|PROD2       | 1       |

我想用django方式制作它,实际上我有

productos = Inventario.objects.filter(cantidad__gt=0).aggregate(Sum('cantidad'))

这只返回cantidad_sum:30

更新 我现在使用此代码获取GROUP BY

query = Inventario.objects.all().query
query.group_by = ['inventario_inventario.producto_id']
productos = QuerySet(query=query, model=Inventario)

但现在我不知道如何制作“SUM”功能:/

1 个答案:

答案 0 :(得分:3)

尝试使用annotate代替aggregateaggregate总结了整个查询集,而annotate为每个组生成了值。如,

productos = Inventario.objects.filter(cantidad__gt=0).values('producto').annotate(sum_cantidad=Sum('cantidad'))

查看django docs了解详情。

相关问题