我有模型:
class M(Model):
re = CharacterField(max_length=50, blank=true)
例如在表中我有:
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
但是是否可以在数据库服务器上执行匹配
?所以用一些表达式将 .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还有。
关于mysql - 字段中的 Django 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35506944/