Skip to content

Commit

Permalink
Provide Model context for DoesNotExit (#742)
Browse files Browse the repository at this point in the history
* Update exceptions.py

* Update queryset.py

* Update queryset.py

* Update exceptions.py

* .

* Update exceptions.py

---------

Co-authored-by: - <->
  • Loading branch information
spacemanspiff2007 authored Jun 3, 2024
1 parent 5610449 commit f3e441e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
20 changes: 20 additions & 0 deletions tortoise/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from tortoise import Model, Type


class BaseORMException(Exception):
"""
Base ORM Exception.
Expand Down Expand Up @@ -52,12 +58,26 @@ class MultipleObjectsReturned(OperationalError):
and more than one object is returned.
"""

def __init__(self, model: "Type[Model]", *args):
self.model: "Type[Model]" = model
super().__init__(*args)

def __str__(self):
return f'Multiple objects returned for "{self.model.__name__}", expected exactly one'


class DoesNotExist(OperationalError):
"""
The DoesNotExist exception is raised when expecting data, such as a ``.get()`` operation.
"""

def __init__(self, model: "Type[Model]", *args):
self.model: "Type[Model]" = model
super().__init__(*args)

def __str__(self):
return f'Object "{self.model.__name__}" does not exist'


class IncompleteInstanceError(OperationalError):
"""
Expand Down
12 changes: 6 additions & 6 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -1071,9 +1071,9 @@ async def _execute(self) -> List[MODEL]:
return instance_list[0]
if not instance_list:
if self._raise_does_not_exist:
raise DoesNotExist("Object does not exist")
raise DoesNotExist(self.model)
return None # type: ignore
raise MultipleObjectsReturned("Multiple objects returned, expected exactly one")
raise MultipleObjectsReturned(self.model)
return instance_list


Expand Down Expand Up @@ -1585,9 +1585,9 @@ async def _execute(self) -> Union[List[Any], Tuple]:
return lst_values[0]
if not lst_values:
if self.raise_does_not_exist:
raise DoesNotExist("Object does not exist")
raise DoesNotExist(self.model)
return None # type: ignore
raise MultipleObjectsReturned("Multiple objects returned, expected exactly one")
raise MultipleObjectsReturned(self.model)
return lst_values


Expand Down Expand Up @@ -1717,9 +1717,9 @@ async def _execute(self) -> Union[List[dict], Dict]:
return result[0]
if not result:
if self.raise_does_not_exist:
raise DoesNotExist("Object does not exist")
raise DoesNotExist(self.model)
return None # type: ignore
raise MultipleObjectsReturned("Multiple objects returned, expected exactly one")
raise MultipleObjectsReturned(self.model)
return result


Expand Down

0 comments on commit f3e441e

Please sign in to comment.