Django ORM - percent sign for like

2019-06-23 12:15发布

问题:

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)

回答1:

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%'])