From c38faebc25a4a4bfa749d97005a43e6bbe6c0be3 Mon Sep 17 00:00:00 2001 From: James Punteney Date: Sat, 16 Jan 2010 13:21:16 -0500 Subject: [PATCH] Adding a get method to the queryset that raises exceptions if more or less than one item is returned --- mongoengine/queryset.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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. """