简体   繁体   English

即使过滤条件不匹配,带有 iregex 的 Django 查询集过滤器也会返回所有对象

[英]Django queryset filter with iregex returns all objects even if filter condition is not matched

I need to query database to get list of users based on case insensitive regex search of emails.我需要查询数据库以根据不区分大小写的正则表达式搜索电子邮件来获取用户列表。

User.objects.filter(email__iregex=f'({"|".join(emails)})')

Here emails is a list containing email ids of users.这里的电子邮件是一个包含用户电子邮件 ID 的列表。 When emails is an empty list the above returns all users from the database.当 emails 是一个空列表时,上面会从数据库中返回所有用户。 I am unable to figure out why this is occuring?我无法弄清楚为什么会发生这种情况? Ideally when emails is empty list, empty queryset should be returned.理想情况下,当电子邮件为空列表时,应返回空查询集。 Can somebody tell me what is wrong with above code.有人能告诉我上面的代码有什么问题吗?

This is perfectly normal, since the regex has no begin/start anchor, and thus an empty regex matches everything .这是完全正常的,因为正则表达式没有开始/开始锚点,因此空的正则表达式匹配所有内容 You can add anchors ^ (the start anchor) and $ (the end anchor) like:您可以添加锚点^ (起始锚点)和$ (结束锚点),例如:

User.objects.filter(email__iregex=f'^({'|'.join(emails)})$')

but still the problem is not solved completely.但问题仍然没有完全解决。 If the email adress contains a dot ( . ) that means "matches any character"), if it contains a question mark ( ? ), it will be interpreted as an optional part.如果电子邮件地址包含一个点 ( . ) 表示“匹配任何字符”),如果它包含一个问号 ( ? ),它将被解释为可选部分。 You can escape these with re.escape(…) [python-doc] :你可以用re.escape(…) [python-doc]来转义这些:

from re import escape as rescape

escaped_emails = '|'.join(map(rescape, emails))
User.objects.filter(email__iregex=f'^({escaped_emails})$')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM