Ghost Ghaith
Ghost Ghaith

Reputation: 29

Django LIKE operation

I'm trying to send a query through Django python I also try to block any sql injection exploits

Can someone explain to me how messaging is done LIKE Query for example

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

It's easy to configure Query like this

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

But when inserting %s Many errors are made when canceling %% From the text, for example

SELECT * FROM admin WHERE name LIKE %s

When Query Done it be like

SELECT * FROM admin WHERE name 'MyTitle'

It is being implemented correctly, but I want it to be set %% among %s LIKE

SELECT * FROM admin WHERE name '%MyTitle%'

Can someone explain to me how to solve this problem

my Simple Script

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

Upvotes: 0

Views: 196

Answers (1)

arheops
arheops

Reputation: 15259

Kindy check this page:

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

That is django-ORM way.

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

That is jango way for raw queries

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

What you are showing is NOT Django code, it is pure python-mysql.

For python-MySQL you should do as you do and it will care about quotes and injections.

But you should do like this

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

Where title_like is like-string.

mysql like string which contains %

Upvotes: 1

Related Questions