我想为以下代码编写原始sql查询。
product_ids = self.env['product.product'].with_context(warehouse=warehouse_id.ids).search([]).filtered(lambda p:p.qty_available > 0)
答案 0 :(得分:0)
乘积qty_available是一个计算字段,计算方法_compute_quantities取决于 _compute_quantities_dict的结果以获取数量dict,而_get_domain_locations则用于解析上下文并返回基于location_ids
的列表。
您需要编写一个获得相同结果的查询。
您可以检查PostgreSQL日志以查看对此python语句执行了多少查询。
以下查询是最后一次获取结果的查询(使用演示数据库生成):
SELECT min("stock_move".id) AS id, count("stock_move".id) AS "product_id_count" , sum("stock_move"."product_qty") AS "product_qty","stock_move"."product_id" as "product_id"
FROM "stock_location" as "stock_move__location_dest_id","stock_location" as "stock_move__location_id","stock_move"
WHERE ("stock_move"."location_dest_id"="stock_move__location_dest_id"."id" AND "stock_move"."location_id"="stock_move__location_id"."id") AND (((("stock_move"."state" in ('waiting','confirmed','assigned','partially_available')) AND ("stock_move"."product_id" in (62,41,40,15,64,65,51,16,17,18,19,20,21,23,24,55,58,60,54,56,57,61,53,52,12,13,14,25,30,26,48,39,36,49,31,34,45,42,5,8,29,43,33,38,46,32,6,27,35,28,44,37,7,50,66,59,67))) AND ("stock_move__location_dest_id"."parent_path"::text like '1/7/%')) AND (NOT (("stock_move__location_id"."parent_path"::text like '1/7/%')))) AND ("stock_move"."location_dest_id"="stock_move__location_dest_id"."id") AND (("stock_move"."company_id" in (1)) OR "stock_move__location_dest_id"."company_id" IS NULL )
GROUP BY "stock_move"."product_id"
ORDER BY "id"
您需要仔细研究_compute_quantities
方法代码以了解Odoo如何计算这些值。
编辑:
考虑以下语句:
self.env['stock.warehouse'].search([('branch_id', '=', self.env.user.branch_id.id)],
order="id desc")
要将上面的语句转换为SQL查询,您需要知道search方法的作用
例如,Odoo将调用_where_calc来计算实现域所需的WHERE
子句,并将('active', '=', 1)
自动添加到域中。
SELECT "stock_warehouse".id FROM "stock_warehouse" WHERE (("stock_warehouse"."active" = %s) AND ("stock_warehouse"."branch_id" = %s)) AND ("stock_warehouse"."company_id" in (%s)) ORDER BY "stock_warehouse"."id" DESC
参数
[True, 1, 1]
最终查询:
SELECT "stock_warehouse".id FROM "stock_warehouse" WHERE (("stock_warehouse"."active" = true) AND ("stock_warehouse"."branch_id" = 1)) AND ("stock_warehouse"."company_id" in (1)) ORDER BY "stock_warehouse"."id" DESC