python - How convert 'tuple' object to str -


i'm trying make search field in app. first want load results, if user request search, show answer.

def get_queryset(self):     pista = self.request.get.get('pesquisar_por')      sql = (     "select t1.codigo, t1.nome, t1.quantidade, t1.preco_venda, t2.nome nome_grupo "+     "from produto t1 "+     "left join grupo t2 on (t1.grupo = t2.codigo) "+     "where t1.status= 'a' ")     if pista not none:         sql = sql + ("and t1.nome %s", ['%'+pista+'%'])     sql = sql + "order t1.nome limit 300"     produtos = produto.objects.using('horus').raw(sql)     return produtos 

but showed error: can't convert 'tuple' object str implicitly.

the error in line: sql = sql + ("and t1.nome %s", ['%'+pista+'%'])

i believe sql concatenation , excution should instead:

sql = sql + "and t1.nome %%s%" 

and pass parameters in .raw() method like:

produtos = produto.objects.using('horus').raw(sql, [pista]) 

i don't remember if need escape % using %%%s%% instead of %%s%, should pass parameters using method signature rather concatenating things avoid sql injection attacks.

check reference: https://docs.djangoproject.com/en/1.8/topics/db/sql/#passing-parameters-into-raw

p.s. have reasons use raw sql instead of orm, i'd reccommend first exhaust ways use orm instead of raw sql. it's you, though.


Comments