Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 25 additions & 20 deletions mongorm/queryset/Q.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,21 @@
MONGO_COMPARISONS = frozenset(['gt', 'lt', 'lte', 'gte', 'exists', 'ne', 'all', 'in', 'elemMatch'])
REGEX_COMPARISONS = {
'contains': ( '%s', '' ),
'icontains': ( '%s', 'i' ),

'iexact': ( '^%s$', 'i' ),

'startswith': ( '^%s', '' ),
'istartswith': ( '^%s', 'i' ),

'endswith': ( '%s$', '' ),
'iendswith': ( '%s$', 'i' ),

'matches': ( None, '' ),
'imatches': ( None, 'i' ),
}
ALL_COMPARISONS = MONGO_COMPARISONS | frozenset(REGEX_COMPARISONS)
ARRAY_VALUE_COMPARISONS = frozenset(['all', 'in'])

class Q(object):
def __init__( self, _query=None, **search ):
Expand All @@ -20,25 +38,6 @@ def toMongo( self, document, forUpdate=False, modifier=None ):

fieldName = name

MONGO_COMPARISONS = ['gt', 'lt', 'lte', 'gte', 'exists', 'ne', 'all', 'in', 'elemMatch']
REGEX_COMPARISONS = {
'contains': ( '%s', '' ),
'icontains': ( '%s', 'i' ),

'iexact': ( '^%s$', 'i' ),

'startswith': ( '^%s', '' ),
'istartswith': ( '^%s', 'i' ),

'endswith': ( '%s$', '' ),
'iendswith': ( '%s$', 'i' ),

'matches': ( None, '' ),
'imatches': ( None, 'i' ),
}
ALL_COMPARISONS = MONGO_COMPARISONS + REGEX_COMPARISONS.keys()
ARRAY_VALUE_COMPARISONS = ['all', 'in']

comparison = None
dereferences = []
if '__' in fieldName:
Expand Down Expand Up @@ -117,7 +116,13 @@ def toMongo( self, document, forUpdate=False, modifier=None ):
else:
newSearch[targetSearchKey] = valueMapper(searchValue)
else:
newSearch[targetSearchKey] = valueMapper(searchValue)
newValue = valueMapper( searchValue )
if isinstance(newValue, dict):
oldValue = newSearch.get( targetSearchKey )
if isinstance(oldValue, dict):
oldValue.update( newValue )
newValue = oldValue
newSearch[targetSearchKey] = newValue

return newSearch

Expand Down
25 changes: 25 additions & 0 deletions tests/test_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,28 @@ class Test(Document):

assert Test.objects.read_preference( 'secondary' ).count( ) >= 3
assert Test.objects.filter( name="John" ).read_preference( ReadPreference.SECONDARY )[0].name == "John"

def test_multiple_operators( ):
"""Tests operators can be combined"""
connect( 'test_mongorm' )

class TestRange(Document):
number = IntegerField( )

# Clear objects so that counts will be correct
TestRange.objects.all( ).delete( )

TestRange( number=0 ).save( )
TestRange( number=1 ).save( )
TestRange( number=2 ).save( )
TestRange( number=3 ).save( )

query = Q( number__gt=0, number__lt=3 )

assert query.toMongo( TestRange ) == {
'number': {
'$lt': 3,
'$gt': 0
}
}
assert TestRange.objects.filter( query ).count( ) == 2