How convert 'tuple' object to str

Question!

I'm trying make a search field in my app. First I want load all results, but if user request the search, show only your 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 as nome_grupo "+
    "FROM produto t1 "+
    "LEFT JOIN grupo t2 on (t1.grupo = t2.codigo) "+
    "WHERE t1.status= 'A' ")
    if pista is not None:
        sql = sql + ("AND t1.nome LIKE %s", ['%'+pista+'%'])
    sql = sql + "ORDER BY t1.nome LIMIT 300"
    produtos = Produto.objects.using('horus').raw(sql)
    return produtos

But this showed this error: Can't convert 'tuple' object to str implicitly.

The error is in this line: sql = sql + ("AND t1.nome LIKE %s", ['%'+pista+'%'])



Answers

You could try with this:

if pista is not None:
    sql = sql + "AND t1.nome LIKE %{pista}%".format(pista=pista)

This will not conver a tuple in str but could help.

By : Gocht


I believe you sql concatenation and excution should be like this instead:

sql = sql + "AND t1.nome LIKE %%s%"

and then pass your parameters in the .raw() method like:

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

I don't remember if you need to escape the % by using %%%s%% instead of just %%s%, but you should definitely pass parameters using the method signature rather than concatenating things yourself to avoid SQL Injection attacks.

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

P.S. You probably have your reasons to use raw sql instead of the ORM, but I'd reccommend to first exhaust the ways you could use the ORM instead of raw sql. It's up to you, though.

By : Gerard


This video can help you solving your question :)
By: admin