简体   繁体   中英

Can't convert SQL to django query (having doesn't work)

I have this SQL:

SELECT 
    stock_id, consignment_id, SUM(qty), SUM(cost) 
FROM
    warehouse_regсonsignmentproduct
WHERE
    product_id = '1'
GROUP BY  
    stock_id, consignment_id
HAVING
    SUM(qty) > 0

I used django ORM to create this query:

regСonsignmentProduct.objects
    .filter(product='1')
    .order_by('period')
    .values('stock', 'consignment')
    .annotate(total_qty=Sum('qty'), total_cost=Sum('cost'))
    .filter(total_qty__gt=0)

But my django query returns an incorrect result.

I think, the problem is in "annotate"

Thanks!

You need to order by the values to force grouping, so:

regСonsignmentProduct.objects.filter(product='1').values(
    'stock', 'consignment'
).annotate(
    total_qty=Sum('qty'),
    total_cost=Sum('cost')
).filter(total_qty__gt=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM