diff --git a/mongoengine/queryset.py b/mongoengine/queryset.py index 06c82cf9..7d89a447 100644 --- a/mongoengine/queryset.py +++ b/mongoengine/queryset.py @@ -18,6 +18,11 @@ class InvalidQueryError(Exception): class OperationError(Exception): pass +class MultipleObjectsReturned(Exception): + pass + +class DoesNotExist(Exception): + pass class Q(object): @@ -290,6 +295,20 @@ class QuerySet(object): return mongo_query + def get(self): + """Retrieve the the matching object raising + 'MultipleObjectsReturned' or 'DoesNotExist' exceptions + if multiple or no results are found. + """ + count = self.count() + if count == 1: + return self[0] + elif count > 1: + raise MultipleObjectsReturned + else: + raise DoesNotExist + + def first(self): """Retrieve the first object matching the query. """