代码之家  ›  专栏  ›  技术社区  ›  user3541631

使用列表参数的原始SQL查询失败

  •  1
  • user3541631  · 技术社区  · 7 年前

    我有以下代码:

     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',而不是list,出现了相同的错误。

    如果我使用没有参数的话,它是工作的。我使用PostgreSQL。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Jonatas CD    7 年前

    根据 SQL notation 对于 IN() 这可能是 IN ('2', '4') 。 因此,您可以尝试以下操作:

    ~'WHERE P.id IN{0}'。格式(tuple(your\u list))~<<不要这样做。

    编辑 :

    警告

    不要在中的原始查询或引号占位符上使用字符串格式 您的SQL字符串!

    Following Django documentation about it ,您可以使用:

    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])