Skip to content

Commit 0ba2e50

Browse files
committed
[soc2010/query-refactor] Implemented __regex and __iregex.
git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2010/query-refactor@13389 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent 3efa619 commit 0ba2e50

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

django/contrib/mongodb/compiler.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import re
2+
13
from pymongo import ASCENDING, DESCENDING
24

35
from django.db.models.sql.datastructures import FullResultSet, EmptyResultSet
@@ -11,6 +13,8 @@ class SQLCompiler(object):
1113
"isnull": lambda params, value_annotation, negated: {"$ne": None} if value_annotation == negated else None,
1214
"gt": lambda params, value_annotation, negated: {"$gt": params[0]},
1315
"in": lambda params, value_annotation, negated: {"$in": params},
16+
"regex": lambda params, value_annotation, negated: re.compile(params[0]),
17+
"iregex": lambda params, value_annotations, negated: re.compile(params[0], re.I)
1418
}
1519

1620
def __init__(self, query, connection, using):
@@ -54,7 +58,9 @@ def make_atom(self, lhs, lookup_type, value_annotation, params_or_value, negated
5458
return column, self.LOOKUP_TYPES[lookup_type](params, value_annotation, negated)
5559

5660
def negate(self, k, v):
57-
if isinstance(v, dict):
61+
# Regex lookups are of the form {"field": re.compile("pattern") and
62+
# need to be negated with $not, not $ne.
63+
if isinstance(v, dict) or isinstance(v, re._pattern_type):
5864
return {k: {"$not": v}}
5965
return {k: {"$ne": v}}
6066

tests/regressiontests/mongodb/tests.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,3 +284,31 @@ def test_in(self):
284284
],
285285
lambda g: g.name,
286286
)
287+
288+
def test_regex(self):
289+
q = Group.objects.create(name="Queen")
290+
e = Group.objects.create(name="The E Street Band")
291+
b = Group.objects.create(name="The Beatles")
292+
293+
self.assertQuerysetEqual(
294+
Group.objects.filter(name__regex="^The"), [
295+
"The E Street Band",
296+
"The Beatles",
297+
],
298+
lambda g: g.name
299+
)
300+
301+
self.assertQuerysetEqual(
302+
Group.objects.filter(name__iregex="^the"), [
303+
"The E Street Band",
304+
"The Beatles",
305+
],
306+
lambda g: g.name
307+
)
308+
309+
self.assertQuerysetEqual(
310+
Group.objects.exclude(name__regex="^The"), [
311+
"Queen",
312+
],
313+
lambda g: g.name,
314+
)

0 commit comments

Comments
 (0)