Django's LIKE operation.
P粉425119739
P粉425119739 2023-08-02 15:55:17
0
1
493
<p>I'm trying to send a query through Django's Python, and I'm also trying to prevent any SQL injection attacks. <br /><br />Can someone explain how the messaging works? For example, an example of a LIKE query. </p><p><br /></p> <pre class="brush:php;toolbar:false;">"SELECT * FROM admin WHERE name LIKE '%myTitle%'</pre> <p>It's easy to configure queries like this. </p> <p><code>cursor.execute("SELECT * FROM admin WHERE name= %s", (_id, ))</code>;</p> <p>But it is easy to make mistakes by canceling the %% in the text when inserting %s, for example. </p> <pre class="brush:php;toolbar:false;">SELECT * FROM admin WHERE name LIKE %s</pre> <p>When the query completes, it will look like this. </p> <pre class="brush:php;toolbar:false;">SELECT * FROM admin WHERE name 'MyTitle'</pre> <p>It is being implemented correctly, but I want %% to be set between %s and LIKE. </p> <pre class="brush:php;toolbar:false;">SELECT * FROM admin WHERE name '%MyTitle%'</pre> <p>Can someone explain how to solve this problem? <br /><br />My simple script is as follows:</p><p><br /></p> <pre class="brush:php;toolbar:false;">from django.db import connection title = "myTitle" query = "SELECT * FROM admin WHERE name LIKE %s" with connection.cursor() as cursor: cursor.execute(query, (title,))</pre> <p><br /></p>
P粉425119739
P粉425119739

reply all(1)
P粉293550575

Please check this page.

What is the SQL ''LIKE" equivalent on Django ORM queries?

That’s Django’s ORM way.

https://docs.djangoproject.com/en/4.2/topics/db/sql/

This is how Django handles raw queries.

>>> query = "SELECT * FROM myapp_person WHERE last_name = %s" % lname
>>> Person.objects.raw(query)

What you are showing is not Django code, but pure Python-MySQL code.

For Python-MySQL you can do it the way you did and it will handle quotes and injection issues.

But you should.


title_like = f"%{title}%"
cursor.execute(query, (title_like,))

title_like is a fuzzy matching string.

mysql like string which contains %

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template