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;