added get-method to fetch exactly one document from the collection. catching pymongo's ObjectId-errors and raising mongoengine's ValidationError instead.
This commit is contained in:
parent
b3cc2f990a
commit
7d6e117f68
@ -6,7 +6,6 @@ import pymongo
|
|||||||
class ValidationError(Exception):
|
class ValidationError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class BaseField(object):
|
class BaseField(object):
|
||||||
"""A base class for fields in a MongoDB document. Instances of this class
|
"""A base class for fields in a MongoDB document. Instances of this class
|
||||||
may be added to subclasses of `Document` to define a document's schema.
|
may be added to subclasses of `Document` to define a document's schema.
|
||||||
@ -76,7 +75,10 @@ class ObjectIdField(BaseField):
|
|||||||
|
|
||||||
def to_mongo(self, value):
|
def to_mongo(self, value):
|
||||||
if not isinstance(value, pymongo.objectid.ObjectId):
|
if not isinstance(value, pymongo.objectid.ObjectId):
|
||||||
return pymongo.objectid.ObjectId(str(value))
|
try:
|
||||||
|
return pymongo.objectid.ObjectId(str(value))
|
||||||
|
except Exception, e:
|
||||||
|
raise ValidationError(e.message)
|
||||||
return value
|
return value
|
||||||
|
|
||||||
def prepare_query_value(self, value):
|
def prepare_query_value(self, value):
|
||||||
|
@ -10,6 +10,10 @@ __all__ = ['queryset_manager', 'Q', 'InvalidQueryError',
|
|||||||
# The maximum number of items to display in a QuerySet.__repr__
|
# The maximum number of items to display in a QuerySet.__repr__
|
||||||
REPR_OUTPUT_SIZE = 20
|
REPR_OUTPUT_SIZE = 20
|
||||||
|
|
||||||
|
class DoesNotExist(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class MultipleObjectsReturned(Exception):
|
class MultipleObjectsReturned(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@ -313,7 +317,17 @@ class QuerySet(object):
|
|||||||
return dataset.first()
|
return dataset.first()
|
||||||
else:
|
else:
|
||||||
raise MultipleObjectsReturned(u'%d items returned, instead of 1' % cnt)
|
raise MultipleObjectsReturned(u'%d items returned, instead of 1' % cnt)
|
||||||
|
|
||||||
|
def get(self, **kwargs):
|
||||||
|
dataset = self.filter(**kwargs)
|
||||||
|
cnt = dataset.count()
|
||||||
|
if cnt == 1:
|
||||||
|
return dataset.first()
|
||||||
|
elif cnt > 1:
|
||||||
|
raise MultipleObjectsReturned(u'%d items returned, instead of 1' % cnt)
|
||||||
|
else:
|
||||||
|
raise DoesNotExist('Document not found')
|
||||||
|
|
||||||
def first(self):
|
def first(self):
|
||||||
"""Retrieve the first object matching the query.
|
"""Retrieve the first object matching the query.
|
||||||
"""
|
"""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user