[英]Can't convert SQL to django query (having doesn't work)
I have this SQL:我有这个 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:我使用 django ORM 创建了这个查询:
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.但是我的 django 查询返回了不正确的结果。
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')
)
.order_by('stock', 'consignment').filter(total_qty__gt=0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.