Adding a get method to the queryset that raises exceptions if more or less than one item is returned
This commit is contained in:
parent
3357b55fbf
commit
c38faebc25
@ -18,6 +18,11 @@ class InvalidQueryError(Exception):
|
|||||||
class OperationError(Exception):
|
class OperationError(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
class MultipleObjectsReturned(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class DoesNotExist(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
class Q(object):
|
class Q(object):
|
||||||
|
|
||||||
@ -290,6 +295,20 @@ class QuerySet(object):
|
|||||||
|
|
||||||
return mongo_query
|
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):
|
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