0

I am a beginner in django , How to write a raw query in django which is similar to

"select * from table where column1 like '%a%'"

I am getting an error

"not enough arguments for format string"

when i just use "select * from table where column1 like 'a' " . it is working .

4
  • What is %a% supposed to be? Commented Apr 11, 2016 at 12:41
  • i am trying to search for all the column1 words which have an "a" some where in them . Commented Apr 11, 2016 at 12:42
  • example : i want to search for all peoples whose name starts with a and have "a" as a character in their names then in raw sql i would write a query like "select * from names_tables where names like '%a%' or names like 'a%' " . Commented Apr 11, 2016 at 12:45
  • I tried using an escape character \ before % it is still giving the same error Commented Apr 11, 2016 at 12:45

1 Answer 1

2

You need to double the percent signs, otherwise they are treated as placeholders.

"select * from table where column1 like '%%a%%'"

When you use raw sql, you can use %s for placeholders, for example:

Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

That means that if you want a literal percent sign, you have to use %%. The Django docs on executing custom SQL directly has an example of this.

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

1 Comment

Thanks it worked !! but can u tell me the reason behind the working . it is some special escape character ?

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.