Teja Reddy
Teja Reddy

Reputation: 571

How to use % while writing a query in django using object.raw() function

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 .

Upvotes: 0

Views: 273

Answers (1)

Alasdair
Alasdair

Reputation: 308779

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.

Upvotes: 2

Related Questions