Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added error for lookup by primary key #759

Merged
merged 7 commits into from
Jun 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions tests/test_model_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
MultipleObjectsReturned,
OperationalError,
ParamsError,
ObjectDoesNotExistError,
ValidationError,
)
from tortoise.expressions import F, Q
Expand Down Expand Up @@ -252,12 +253,26 @@ async def test_index_access(self):
self.assertEqual(obj, self.mdl)

async def test_index_badval(self):
with self.assertRaises(KeyError):
with self.assertRaises(ObjectDoesNotExistError) as cm:
await self.cls[100000]
the_exception = cm.exception
# For compatibility reasons this should be an instance of KeyError
self.assertIsInstance(the_exception, KeyError)
self.assertIs(the_exception.model, self.cls)
self.assertEqual(the_exception.pk_name, "id")
self.assertEqual(the_exception.pk_val, 100000)
self.assertEqual(str(the_exception), f"{self.cls.__name__} has no object with id=100000")

async def test_index_badtype(self):
with self.assertRaises(KeyError):
with self.assertRaises(ObjectDoesNotExistError) as cm:
await self.cls["asdf"]
the_exception = cm.exception
# For compatibility reasons this should be an instance of KeyError
self.assertIsInstance(the_exception, KeyError)
self.assertIs(the_exception.model, self.cls)
self.assertEqual(the_exception.pk_name, "id")
self.assertEqual(the_exception.pk_val, "asdf")
self.assertEqual(str(the_exception), f"{self.cls.__name__} has no object with id=asdf")

async def test_clone(self):
mdl2 = self.mdl.clone()
Expand Down
16 changes: 15 additions & 1 deletion tortoise/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from tortoise import Model, Type
Expand Down Expand Up @@ -66,6 +66,20 @@ def __str__(self):
return f'Multiple objects returned for "{self.model.__name__}", expected exactly one'


class ObjectDoesNotExistError(OperationalError, KeyError):
"""
The DoesNotExist exception is raised when an item with the passed primary key does not exist
"""

def __init__(self, model: "Type[Model]", pk_name: str, pk_val: Any):
self.model: "Type[Model]" = model
self.pk_name: str = pk_name
self.pk_val: Any = pk_val

def __str__(self):
return f"{self.model.__name__} has no object with {self.pk_name}={self.pk_val}"


class DoesNotExist(OperationalError):
"""
The DoesNotExist exception is raised when expecting data, such as a ``.get()`` operation.
Expand Down
3 changes: 2 additions & 1 deletion tortoise/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
IntegrityError,
OperationalError,
ParamsError,
ObjectDoesNotExistError,
)
from tortoise.fields.base import Field
from tortoise.fields.data import IntField
Expand Down Expand Up @@ -783,7 +784,7 @@ async def _getbypk(cls: Type[MODEL], key: Any) -> MODEL:
try:
return await cls.get(pk=key)
except (DoesNotExist, ValueError):
raise KeyError(f"{cls._meta.full_name} has no object {repr(key)}")
raise ObjectDoesNotExistError(cls, cls._meta.pk_attr, key)

def clone(self: MODEL, pk: Any = EMPTY) -> MODEL:
"""
Expand Down