Adding a get method to the queryset that raises exceptions if more or less than one item is returned
This commit is contained in:
		| @@ -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. | ||||
|         """ | ||||
|   | ||||
		Reference in New Issue
	
	Block a user