Question

I know this may be something stupid but I decided to ask any way.

I've been trying to query something like:

 cursor.execute("select col1, col2   \
                    from my_tablem \
                    where afield like '%%s%'
                    and secondfield = %s
                    order by 1 desc " % (var1, var2) )

But I get an error in the like sentence. It doesn't like the extra % which I need to get all the results that contains the first %s value.

Ideas?

TIA!

Was it helpful?

Solution

First, why aren't you using the Django ORM for this?

MyClass.objects.filter( aField__contains=var1, secondField__exact=var2 )

Second, be sure you're getting the SQL you expect.

stmt= "select... afield like '%%%s%%' and secondfield = '%s'..." % ( var1, var2 )
print stmt
cursor.execute( stmt )

Third, your method has a security hole called a SQL Injection Attack. You really should not be doing SQL like this.

If you absolutely must do things outside Django's ORM, you have to use bind variables in your query, not string substitution. See http://docs.djangoproject.com/en/dev/topics/db/sql/#performing-raw-sql-queries.

OTHER TIPS

can hack string '%' into search string?

var1 = '%' + var1 + '%'

then query normally:

cursor.execute("select col1, col2 
                    from my_tablem                     where afield like %s
                    and secondfield = %s
                    order by 1 desc " , [var1, var2] )

I had a similar issue. I was trying to search among concatenated name fields. My query was something like:

sql = """SELECT * from auth_user WHERE lower(first_name) || ' ' || lower(last_name) = '%%%s%%'"""

User.objects.raw(sql, [q])

The problem was that the %% were breaking my query. The solution I wound up with was:

q = '%' + q + '%'
sql = """SELECT * from auth_user WHERE lower(first_name) || ' ' || lower(last_name) = %s"""

User.objects.raw(sql, [q])
Persona.objects.raw("**SELECT** id,concat_ws(' ',nombre,apellido) **AS** nombre_completo **FROM** persona **GROUP BY** id **HAVING** concat_ws(' ',nombre,apellido) **ILIKE** '%s' " % ('%%' + query + '%%'))

(Postgresql 9.1)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top