Skip to content

Commit 94adc20

Browse files
author
Jorge Bastida
committed
First as_pymongo implementation
1 parent 653c425 commit 94adc20

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

mongoengine/queryset.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,7 @@ def __init__(self, document, collection):
353353
self._slave_okay = False
354354
self._iter = False
355355
self._scalar = []
356+
self._as_pymongo = False
356357

357358
# If inheritance is allowed, only return instances and instances of
358359
# subclasses of the class being used
@@ -1002,6 +1003,10 @@ def next(self):
10021003
if self._scalar:
10031004
return self._get_scalar(self._document._from_son(
10041005
self._cursor.next()))
1006+
1007+
if self._as_pymongo:
1008+
return self._cursor.next()
1009+
10051010
return self._document._from_son(self._cursor.next())
10061011
except StopIteration, e:
10071012
self.rewind()
@@ -1602,6 +1607,13 @@ def values_list(self, *fields):
16021607
"""An alias for scalar"""
16031608
return self.scalar(*fields)
16041609

1610+
def as_pymongo(self):
1611+
"""Instead of returning Document instances, return raw values from
1612+
pymongo.
1613+
"""
1614+
self._as_pymongo = True
1615+
return self
1616+
16051617
def _sub_js_fields(self, code):
16061618
"""When fields are specified with [~fieldname] syntax, where
16071619
*fieldname* is the Python name of a field, *fieldname* will be

tests/test_queryset.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3691,6 +3691,22 @@ class Bar(Document):
36913691
ak = list(Bar.objects(foo__match={'shape': "square", "color": "purple"}))
36923692
self.assertEqual([b1], ak)
36933693

3694+
def test_as_pymongo(self):
3695+
3696+
class User(Document):
3697+
id = ObjectIdField('_id')
3698+
name = StringField()
3699+
age = IntField()
3700+
3701+
User.drop_collection()
3702+
User(name="Bob Dole", age=89).save()
3703+
User(name="Barack Obama", age=51).save()
3704+
3705+
users = [u for u in User.objects.only('name').as_pymongo()]
3706+
self.assertTrue(isinstance(users[0], dict))
3707+
self.assertTrue(isinstance(users[1], dict))
3708+
self.assertEqual(users[0]['name'], 'Bob Dole')
3709+
self.assertEqual(users[1]['name'], 'Barack Obama')
36943710

36953711
if __name__ == '__main__':
36963712
unittest.main()

0 commit comments

Comments
 (0)