Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM - percent sign for like

On my site user should have an ability to filter numbers, like *123*321*, that will match "666 123 555 321 111" or LIKE '%123%321%'.

By default django's orm escapes %-sign. I can use regex, or raw query, but is there some workaround?

UPD: i'll place it here for displaying another way.

integer_search = [] # for colorizing found substrings
if actual['integer']:
    integer_match = filter(None, actual['international'].split('*'))
    integer_search = integer_match
    integer_match = ''.join('%s[[:digit:]]*' % i for i in integer_match)
    integers = integers.filter(international__regex=integer_match)
like image 694
night-crawler Avatar asked May 29 '12 13:05

night-crawler


1 Answers

Yes, Django replaces all the % and _. From docs:

This means things should work intuitively, so the abstraction doesn't leak. For example, to retrieve all the entries that contain a percent sign, just use the percent sign as any other character

I would recommend you to use extra method. It is not really raw sql, although looks hacky:

YourModel.objects.extra(where=['title LIKE %s'], params=['%123%321%'])
like image 174
San4ez Avatar answered Sep 27 '22 19:09

San4ez