开发者

Query filtering in Django with sqlite

开发者 https://www.devze.com 2023-01-15 00:09 出处:网络
I\'ve tried the following query with Django, def search(search_text): q= Info.objects.filter(title__contains=str(search_text))

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 ad开发者_运维知识库d the quotes around the search_text so that the query succeeds ?

I'm using Djanog with sqlite3


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消