在Odoo中的SQL查询中使用ID列表

时间:2019-07-19 06:51:46

标签: sql python-3.x postgresql odoo

需要将id列表传递给where子句中的sql查询。 product_id是many2many字段。 我的代码是

query = """
                    SELECT pt.name as product,sl.price_unit as price,sum(sl.qty_invoiced) as quantity from sale_order_line sl
                    JOIN sale_order so ON so.id = sl.order_id
                    JOIN product_product pp ON pp.id = sl.product_id
                    JOIN product_template pt ON pt.id = pp.product_tmpl_id
                    WHERE so.date_order >='"""+str(obj.start_date)+"""' 
                    and so.date_order <= '"""+str(obj.end_date)+"""' 
                    and so.partner_id ="""+str(obj.customer_id.id)+""" 
                    and sl.invoice_status = 'invoiced'
        """ 
    if obj.product_id:
        query +=""" and sl.product_id in """+str(obj.product_id.ids)
    query += """GROUP BY product,price"""

语法错误sl.product_id in [13017, 11253, 1395] near '['

3 个答案:

答案 0 :(得分:1)

在SQL中,IN子句应使用()而不是[],因此请尝试以这种方式格式化IN值序列

sl.product_id in (3017, 11253, 1395) 

答案 1 :(得分:1)

解决方案, 将ID列表转换为元组

if obj.product_id:
        query +=""" and sl.product_id in %s"""
    query += """GROUP BY product,price"""
    self.env.cr.execute(query, [tuple(obj.product_id.ids)])

答案 2 :(得分:1)

不建议直接在查询中渲染参数 像这样,这是一个坏习惯,您不应该使用任何编程语言(SQL注入技巧)来做到这一点。

只需使用传递给您的元组参数来执行调用。

        query = """
                            SELECT pt.name as product,sl.price_unit as price,sum(sl.qty_invoiced) as quantity 
                            FROM sale_order_line sl
                                JOIN sale_order so ON so.id = sl.order_id
                                JOIN product_product pp ON pp.id = sl.product_id
                                JOIN product_template pt ON pt.id = pp.product_tmpl_id
                            WHERE so.date_order >= %s 
                                and so.date_order <= %s 
                                and so.partner_id = %s 
                                and sl.invoice_status = 'invoiced'
                """ 


        # remember to keep the params in the same order when you use a tuple for params
        # you can use dictionary, you can read about it, instead of %s you write %(some_key)s
        query_params = (obj.start_date,
                        obj.end_date,
                        obj.customer_id.id)
        if obj.product_id:
                query += """ and sl.product_id in  %s """
                query_params += (tuple(obj.product_id.ids),)

        query += """ GROUP BY product,price """

        self.env.cr.execute(query, query_params)