Django's LIKE operation.
P粉425119739
P粉425119739 2023-08-02 15:55:17
0
1
402

I'm trying to send a query through Django's Python, and I'm also trying to prevent any SQL injection attacks.

Can someone explain how the messaging works? For example, an example of a LIKE query.


"SELECT * FROM admin WHERE name LIKE '%myTitle%'

It's easy to configure queries like this.

cursor.execute("SELECT * FROM admin WHERE name= %s", (_id, ));

But it is easy to make mistakes by canceling the %% in the text when inserting %s, for example.

SELECT * FROM admin WHERE name LIKE %s

When the query completes, it will look like this.

SELECT * FROM admin WHERE name 'MyTitle'

It is being implemented correctly, but I want %% to be set between %s and LIKE.

SELECT * FROM admin WHERE name '%MyTitle%'

Can someone explain how to solve this problem?

My simple script is as follows:


from django.db import connection title = "myTitle" query = "SELECT * FROM admin WHERE name LIKE %s" with connection.cursor() as cursor: cursor.execute(query, (title,))


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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!