First as_pymongo implementation

This commit is contained in:
Jorge Bastida 2012-12-07 11:20:27 +00:00
parent 653c4259ee
commit 94adc207ad
2 changed files with 28 additions and 0 deletions

View File

@ -353,6 +353,7 @@ class QuerySet(object):
self._slave_okay = False
self._iter = False
self._scalar = []
self._as_pymongo = False
# If inheritance is allowed, only return instances and instances of
# subclasses of the class being used
@ -1002,6 +1003,10 @@ class QuerySet(object):
if self._scalar:
return self._get_scalar(self._document._from_son(
self._cursor.next()))
if self._as_pymongo:
return self._cursor.next()
return self._document._from_son(self._cursor.next())
except StopIteration, e:
self.rewind()
@ -1602,6 +1607,13 @@ class QuerySet(object):
"""An alias for scalar"""
return self.scalar(*fields)
def as_pymongo(self):
"""Instead of returning Document instances, return raw values from
pymongo.
"""
self._as_pymongo = True
return self
def _sub_js_fields(self, code):
"""When fields are specified with [~fieldname] syntax, where
*fieldname* is the Python name of a field, *fieldname* will be

View File

@ -3691,6 +3691,22 @@ class QueryFieldListTest(unittest.TestCase):
ak = list(Bar.objects(foo__match={'shape': "square", "color": "purple"}))
self.assertEqual([b1], ak)
def test_as_pymongo(self):
class User(Document):
id = ObjectIdField('_id')
name = StringField()
age = IntField()
User.drop_collection()
User(name="Bob Dole", age=89).save()
User(name="Barack Obama", age=51).save()
users = [u for u in User.objects.only('name').as_pymongo()]
self.assertTrue(isinstance(users[0], dict))
self.assertTrue(isinstance(users[1], dict))
self.assertEqual(users[0]['name'], 'Bob Dole')
self.assertEqual(users[1]['name'], 'Barack Obama')
if __name__ == '__main__':
unittest.main()