find_one now supports using just an object id
This commit is contained in:
parent
744077b150
commit
90e27cc87d
@ -1,5 +1,7 @@
|
|||||||
from connection import _get_db
|
from connection import _get_db
|
||||||
|
|
||||||
|
import pymongo
|
||||||
|
|
||||||
|
|
||||||
class QuerySet(object):
|
class QuerySet(object):
|
||||||
"""A set of results returned from a query. Wraps a MongoDB cursor,
|
"""A set of results returned from a query. Wraps a MongoDB cursor,
|
||||||
@ -74,15 +76,26 @@ class CollectionManager(object):
|
|||||||
return mongo_query
|
return mongo_query
|
||||||
|
|
||||||
def find(self, **query):
|
def find(self, **query):
|
||||||
"""Query the collection for document matching the provided query.
|
"""Query the collection for documents matching the provided query.
|
||||||
"""
|
"""
|
||||||
query = self._transform_query(**query)
|
query = self._transform_query(**query)
|
||||||
query['_types'] = self._document._class_name
|
query['_types'] = self._document._class_name
|
||||||
return QuerySet(self._document, self._collection.find(query))
|
return QuerySet(self._document, self._collection.find(query))
|
||||||
|
|
||||||
def find_one(self, **query):
|
def find_one(self, object_id=None, **query):
|
||||||
"""Query the collection for document matching the provided query.
|
"""Query the collection for document matching the provided query.
|
||||||
"""
|
"""
|
||||||
query = self._transform_query(**query)
|
if object_id:
|
||||||
query['_types'] = self._document._class_name
|
# Use just object_id if provided
|
||||||
return self._document._from_son(self._collection.find_one(query))
|
if not isinstance(object_id, pymongo.objectid.ObjectId):
|
||||||
|
object_id = pymongo.objectid.ObjectId(object_id)
|
||||||
|
query = object_id
|
||||||
|
else:
|
||||||
|
# Otherwise, use the query provided
|
||||||
|
query = self._transform_query(**query)
|
||||||
|
query['_types'] = self._document._class_name
|
||||||
|
|
||||||
|
result = self._collection.find_one(query)
|
||||||
|
if result is not None:
|
||||||
|
result = self._document._from_son(result)
|
||||||
|
return result
|
||||||
|
@ -97,6 +97,10 @@ class CollectionManagerTest(unittest.TestCase):
|
|||||||
person = self.Person.objects.find_one(age__lt=30)
|
person = self.Person.objects.find_one(age__lt=30)
|
||||||
self.assertEqual(person.name, "User A")
|
self.assertEqual(person.name, "User A")
|
||||||
|
|
||||||
|
# Find a document using just the object id
|
||||||
|
person = self.Person.objects.find_one(person1._id)
|
||||||
|
self.assertEqual(person.name, "User A")
|
||||||
|
|
||||||
def test_find_embedded(self):
|
def test_find_embedded(self):
|
||||||
"""Ensure that an embedded document is properly returned from a query.
|
"""Ensure that an embedded document is properly returned from a query.
|
||||||
"""
|
"""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user