我有模特:
class M(Model):
re = CharacterField(max_length=50, blank=true)
例如,在表格中我有:
table m
----------------
| id | re |
----------------
| 1 | \d+ |
| 2 | \:abc |
----------------
我想通过存储在re字段中的regexp找到一些与我的输入字符串(inp)匹配的对象,参见示例:
inp = ":abc"
for m in M.objects.all():
if re.match(m.re, inp)
print("{} matched".format(m.id)) # 2 matched
但是可以在DB服务器上执行匹配吗?所以用一些表达式将.all()替换为’.filter’?
解决方法:
对于正则表达式匹配,您需要在过滤器调用中的fieldname之后使用__iregex:
M.objects.filter(re__iregex=inp)
查看official documentation以获取更多信息
编辑
如果您想要反向操作(检查数据库中保存的任何正则表达式是否与您的值匹配),您不能使用简单的过滤器,但您可以定义自定义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也是.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。