5

I have a raw sql query which is always giving error while executing. Here is my query

Users.objects.raw('select target, username from users where location like \'%s%%\' and date(modified) = \'2011-06-14\'',[location])

I am taking the location = 'BUILD'

Location values would be 'BUILD_A', 'BUILD_B','BUILD_C'.

When I am executing the raw sql, below is the error I am getting.

DatabaseError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'BUILD'%' and date(modified) = '2011-06-14'' at line 1")

In MySQL terms I need to execute the following query:

Select target, username from users where location like 'BUILD%' and target = '2011-06-14'

I have googled it but could not able to get it. Please some one help me

2 Answers 2

9

I have solved my problem in this way.

location = location + '%'

users_list = Users.objects.raw('select target, username from users where location like %s and date(modified) = %s',tuple([location,date]))

The above statement executes perfectly without any error and I can able to render the results in template also.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's such a simple solution to make LIKE and ILIKE queries work in raw.
-1

Below query works for me,

query = "Select target, username from users where location like 'BUILD%'"
results = Users.objects.raw(query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.