tags:

views:

42

answers:

2

I want to be able to use wildcards in my django queries used for searching. However as the documentation says:

Entry.objects.filter(headline__contains='%')

Will result in SQL that looks something like this:

SELECT ... WHERE headline LIKE '%\%%';

How do I tell django to not escape % and _ in a query. Or is there another way to implement wildcard search in django (apart from writing the sql directly)?

A: 

You can use the extra() method to insert a custom where clause:

Entry.objects.extra(where="headline LIKE '%'")
muksie
This is probably the only way to do general wildcards, but also remember that different DB backends do this differently and this won't hide the differences for you. In some you'll need to say `LIKE 'string \'with\' escapes' ESCAPE '\'` if your string may have escapes. In Postgresql, you need to say `LIKE E'string \'with\' escapes'`.
Glenn Maynard
+1  A: 

headline__contains='%' would mean headline is anything, no? In which case why include it in the query?

Ned Batchelder
Err, because it's an example, of course...
Glenn Maynard