Django do group by with sum

0

I have a Warehouse Movements model, I want to take stock per warehouse of an item. The SQL query is:

select  almacen_id, sum(uentrada), sum(usalida) from Almacen_movimiento 
    where articulo_id = 2
    group by almacen_id

I try this:

mv = Movimiento.objects.order_by('almacen').annotate(ent=Sum('uentrada')).annotate(sal=Sum('usalida')

(as it is a procedure within the model article and use _set does not need the clausua where.

The point is that some stores go double, when it should not.

How can I do it?

    
asked by Cecilior 05.11.2016 в 19:10
source

2 answers

0

you can try it this way

Movimiento.objects.order_by('almacen').annotate(
     ent = Sum('uentrada'),
     sal = Sum('usalida')
)
    
answered by 05.11.2016 в 23:00
0

Try this:

Movimiento.objects.filter(articulo_id=2).values('almacen').annotate(
    ent=Sum('uentrada'),
    sal = Sum('usalida')
).order_by('almacen')
    
answered by 07.11.2016 в 16:24