Added pretty query format, cursor limit and skip

This commit is contained in:
Harry Marr
2009-11-19 17:47:02 +00:00
parent 5fcb5aba7c
commit 0674e3c013
2 changed files with 66 additions and 4 deletions

View File

@@ -20,6 +20,19 @@ class QuerySet(object):
"""
return self._cursor.count()
def limit(self, n):
"""Limit the number of returned documents to.
"""
self._cursor.limit(n)
# Return self to allow chaining
return self
def skip(self, n):
"""Skip n documents before returning the results.
"""
self._cursor.skip(n)
return self
def __iter__(self):
return self
@@ -41,12 +54,35 @@ class CollectionManager(object):
_id = self._collection.save(document._to_mongo())
document._id = _id
def find(self, query=None):
def _transform_query(self, **query):
"""Transform a query from Django-style format to Mongo format.
"""
operators = ['neq', 'gt', 'gte', 'lt', 'lte', 'in', 'nin', 'mod',
'all', 'size', 'exists']
mongo_query = {}
for key, value in query.items():
parts = key.split('__')
# Check for an operator and transform to mongo-style if there is
if parts[-1] in operators:
op = parts.pop()
value = {'$' + op: value}
key = '.'.join(parts)
mongo_query[key] = value
return mongo_query
def find(self, **query):
"""Query the collection for document matching the provided query.
"""
if query:
query = self._transform_query(**query)
return QuerySet(self._document, self._collection.find(query))
def find_one(self, query=None):
def find_one(self, **query):
"""Query the collection for document matching the provided query.
"""
if query:
query = self._transform_query(**query)
return self._document._from_son(self._collection.find_one(query))