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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With