本文介绍了Django ORM - 喜欢的百分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站用户应该有能力过滤数字,如 * 123 * 321 * ,匹配666 123 555 321 111或 LIKE'%123%321%'

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%'.

默认情况下django's orm转义。我可以使用正则表达式或原始查询,但是是否有一些解决方法?

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

UPD:我将其放在这里显示另一种方式。

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)


推荐答案

p>是的,Django替换所有的 _ 。从:

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

我建议您使用方法。它不是真正的原始sql,虽然看起来很古怪:

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

这篇关于Django ORM - 喜欢的百分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 02:40