字段中的 Django 正则表达式

Django regexp in field

我有型号:

class M(Model):
    re = CharacterField(max_length=50, blank=true)

例如 table 我有:

table m
----------------
| id  |  re    |
----------------
|  1  |  \d+   |
|  2  |  \:abc |
----------------

我想通过存储在 re 字段中的正则表达式找到一些与我的输入字符串 (inp) 匹配的对象,参见示例:

inp = ":abc"
for m in M.objects.all():
    if re.match(m.re, inp)
        print("{} matched".format(m.id)) # 2 matched

但是可以在数据库服务器上执行match吗?所以用一些表达式替换 .all() 到 '.filter'?

对于正则表达式匹配,您需要在 filter 调用中的字段名后使用 __iregex

    M.objects.filter(re__iregex=inp)

查看 official documentation 以获取更多信息


编辑

如果你想要反向操作(检查数据库中保存的任何正则表达式是否与你的值匹配)你不能使用简单的 filter 但你可以定义你的自定义 Manager

class CurrentManager(models.Manager):
    def match(self, value):
        objects = super(CurrentManager, self).get_query_set().all()

        #here your code
        objects = [o for o in objects if re.match(o, value)]

        return objects

class M(Model):
    re = CharacterField(max_length=50, blank=true)
    objects = RegexManager()

#usage
matched = M.objects.match('123')

也看看这个question

首先,\d 没有被 MySQL 处理。请改用 [0-9][[:digit:]].

其次,要在 SQL 中执行正则表达式,让您的应用构建

'[0-9]+|:abc'

然后将其构建到查询中。

但您可能想要锚定正则表达式:

'^([0-9]+|:abc)$'
for m in M.objects.filter().extra(where=["'{}' RLIKE `m`.`re`".format(inp)])
    print("{} matched".format(m.id))