rampr
rampr

Reputation: 1947

Query filtering in Django with sqlite

I've tried the following query with Django,

def search(search_text):
    q  = Info.objects.filter(title__contains=str(search_text))
    print q.query

The query that get printed is

SELECT "d"."id", "d"."foo" FROM "d_info" WHERE "d_info"."title" LIKE %hello% ESCAPE '\' 

The query fails because the text after LIKE doesn't have quotes around it. The query succeeds when I run the query on the sql prompt with quotes around the text after LIKE like below

SELECT "d"."id", "d"."foo" FROM "d_info" WHERE "d_info"."title" LIKE '%hello%' ESCAPE '\' 

How do I get Django to add the quotes around the search_text so that the query succeeds ?

I'm using Djanog with sqlite3

Upvotes: 1

Views: 3899

Answers (2)

rampr
rampr

Reputation: 1947

Posting my comment above as the answer

It so turns out the query works within Django, but when asked to print the query and if I copy the query printed and execute it in a mysql shell or sqlite shell, it doesn't work. Django is probably printing the query wrong

Upvotes: 0

Manoj Govindan
Manoj Govindan

Reputation: 74715

I tried this out with Postgresql 8.3. The query is generated without quotes. However executing the filter returns a valid queryset with expected instances. Can you try executing

q = Info.objects.filter(title__contains=str(search_text))
print q.count()

and see if it works?

Upvotes: 1

Related Questions