Django ORM - percent sign for like

让人想犯罪 __ 提交于 2019-12-10 14:53:16

问题


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


来源:https://stackoverflow.com/questions/10800680/django-orm-percent-sign-for-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!