First as_pymongo implementation
This commit is contained in:
		@@ -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
 | 
			
		||||
 
 | 
			
		||||
@@ -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()
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user