I am using raw queries in a project, and I am concerned that the inputs are not being escaped. Here’s an example:
…
myquery = """select * from identifiers \
join books on identifiers.bookid = books.id \
left join covers on identifiers.identifier = covers.idvalue \
where identifiers.identifier = ""%(barcode)s"" ;"""
thevalues = {'barcode': barcode}
theset = Books.objects.raw(myquery, thevalues)
print('theset.query: ', theset.query)
…
When I print theset.query
the characters that should be escaped in barcode
are not, ie:
select * from identifiers
join books on identifiers.bookid = books.id
left join covers on identifiers.identifier = covers.idvalue
where identifiers.identifier = ""978150360"922;8"" ;
Where I think it should look like this:
select * from identifiers
join books on identifiers.bookid = books.id
left join covers on identifiers.identifier = covers.idvalue
where identifiers.identifier = ""978150360\"922\;8"" ;
In a similar vein I am trying LIKE
queries:
myquery = """select * from identifiers \
join books on identifiers.bookid = books.id \
left join covers on identifiers.identifier = covers.idvalue \
where identifiers.identifier LIKE ""%%%(barcode)s%%"" ;"""
thevalues = {'barcode': barcode}
theset = Books.objects.raw(myquery, thevalues)
print('theset.query: ', theset.query)
In this case the query runs in Django ok, but finds no records, whereas when I directly use the output from theset.query
I get two hits.
I suspect in the former case it is being escaped, but not showing me for some reason, and the letter I’m just not quite getting the formatting right – but would appreciate some pointers.
Someone is probably wondering why the raw queries? I tried building a model for this, with standard Django queries, but kept getting complaints that some of the fields I was trying to build joins between did not have a unique
attribute - which in the case of this set of records makes absolutely no sense.