我有以下代码:
products = Product.objects.raw(
'SELECT DISTINCT ON(I.product_id) P.id, P.name, P.desc, C.name AS ram, I.image '
'FROM products_product AS P '
'LEFT JOIN categories AS RPC ON P.id = RPC.product_id '
'LEFT JOIN company AS CP ON P.company_id = CP.id '
'LEFT JOIN category AS C ON RPC.category_id = C.id '
'LEFT JOIN image AS I ON I.product_id = P.id '
'WHERE P.id IN %s', list
)
我收到以下错误:
not all arguments converted during string formatting
我试图使用[2,4]或[' 2',' 4']而不是列表,同样的错误。
如果我使用没有参数正在工作。我使用PostgreSQL。
答案 0 :(得分:2)
根据IN()
的{{1}},这可能是IN ('2', '4')
。
所以你可以尝试类似的东西:
〜'WHERE P.id IN {0}'。format(tuple(your_list))〜<<不。
修改强>:
警告
不要在原始查询或引号占位符上使用字符串格式 你的SQL字符串!
SQL notation,您可以使用:
products = Product.objects.raw(
'SELECT DISTINCT ON(I.product_id) P.id, P.name, P.desc, C.name AS ram, I.image '
'FROM products_product AS P '
'LEFT JOIN categories AS RPC ON P.id = RPC.product_id '
'LEFT JOIN company AS CP ON P.company_id = CP.id '
'LEFT JOIN category AS C ON RPC.category_id = C.id '
'LEFT JOIN image AS I ON I.product_id = P.id '
'WHERE P.id IN %s', params=[your_list])