开发者

SQL LIKE in Django/Python

开发者 https://www.devze.com 2022-12-19 03:07 出处:网络
I\'m trying to run a query like this: SELECT * FROM MyTable WHERE FirstName LIKE \'%[user inputted value here]%\'

I'm trying to run a query like this:

SELECT * 
FROM 
    MyTable 
WHERE 
    FirstName LIKE '%[user inputted value here]%' 
    OR 
    LastName LIKE '%[that same user inputted value]%' 
    AND 
    UserID = some number

When I run the query using cursor.execute(), the inputted values are going to be escaped and quoted, which is causing an incorrect query to run. Is there a way to prevent the user inputted values from being quoted?

I'd prefer a solution not using Django's ORM, since the actual query is much more complica开发者_运维问答ted than my example.


Use foo__contains=realvaluehere in your queries.


Hmm, looks like I overestimated the escapy-ness of the API. This works exactly how I want it to

# add wildcards to query, these are **not** escaped
q = "%" + q + "%"
cursor = connection.cursor()
cursor.execute("SELECT * 
                FROM MyTable 
                WHERE 
                  LastName LIKE %s 
                  AND 
                  FirstName LIKE %s 
                  AND 
                  UserID = %s", [q, q, user_id])
results = cursor.fetchall()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号