Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to pass parameters containing string into Django Raw sql

I have bunch of complicated sql queries that I need to execute on Django and Raw SQL seems to be the only option. My parameters are strings and can be empty. The reason for being empty is that I have conditional statements above, and depending on that the correct sql needs to be executed. But when the ra sql is run, django actually puts quotes (which I use to denote strings) in the sql and so it throws an error.

I have simplified the query to show the problem I am facing. The following query when executed throws an error.

select_cond = ''
where_cond = 'id = 109'

qraw = Book.objects.raw(
        "\
        SELECT  id %s\
        FROM book\
        WHERE %s\
        ",
        [select_cond, where_cond]
)

The error is due to it being translated as follows. The quotes actually get in the sql and so it won't execute. Any idea on how I can fix this?

 SELECT  id ''
 FROM book
 WHERE 'id = 109'
 ORDER BY id DESC;
like image 270
bachkoi32 Avatar asked Oct 13 '25 08:10

bachkoi32


1 Answers

Django provides a 'params' argument for raw that avoids the potential for SQL injection attacks. As @alecxe's example shows, triple quotes in python are a great way to define a multi-line variable and avoid any backslash line escapes. Here's a proposed safe solution the "Django way":

select_cond = condition
where_cond = condition

qraw = Book.objects.raw("""
    SELECT
        id, %(select_cond)s
    FROM
        book
    WHERE
        %(where_cond)s
    """, params={'select_cond': select_cond, 'where_cond': where_cond})

Just replace condition placeholders with appropriate values.

like image 78
Brad Avatar answered Oct 14 '25 22:10

Brad