diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5699555fd..21609c77c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,9 @@ Changelog ========= +0.15.16 +- ``get_or_none(...)`` now raise MultipleObjectsReturnederror if multiple object fetched. (#298) + 0.15.15 ------- - Add ability to suppply a ``to_field=`` parameter for FK/O2O to a non-PK but still uniquely indexed remote field. (#287) diff --git a/tests/test_queryset.py b/tests/test_queryset.py index a1c50fea2..348bccfa2 100644 --- a/tests/test_queryset.py +++ b/tests/test_queryset.py @@ -148,15 +148,15 @@ async def test_first(self): ) async def test_get_or_none(self): - # Test first - self.assertEqual( - (await IntFields.all().order_by("intnum").get_or_none(intnum__gte=40)).intnum, 40 - ) + self.assertEqual((await IntFields.all().get_or_none(intnum=40)).intnum, 40) self.assertEqual( await IntFields.all().order_by("intnum").get_or_none(intnum__gte=400), None ) + with self.assertRaises(MultipleObjectsReturned): + await IntFields.all().order_by("intnum").get_or_none(intnum__gte=40) + async def test_get(self): await IntFields.filter(intnum__gte=70).update(intnum_null=80) diff --git a/tortoise/queryset.py b/tortoise/queryset.py index 687105fbf..550826f2e 100644 --- a/tortoise/queryset.py +++ b/tortoise/queryset.py @@ -482,12 +482,12 @@ def get(self, *args: Q, **kwargs: Any) -> QuerySetSingle[MODEL]: queryset._get = True return queryset # type: ignore - def get_or_none(self, *args: Q, **kwargs: Any) -> QuerySetSingle[MODEL]: + def get_or_none(self, *args: Q, **kwargs: Any) -> QuerySetSingle[Optional[MODEL]]: """ Fetch exactly one object matching the parameters. """ queryset = self.filter(*args, **kwargs) - queryset._limit = 1 + queryset._limit = 2 queryset._single = True return queryset # type: ignore @@ -608,9 +608,11 @@ async def _execute(self) -> List[MODEL]: raise DoesNotExist("Object does not exist") raise MultipleObjectsReturned("Multiple objects returned, expected exactly one") if self._single: + if len(instance_list) == 1: + return instance_list[0] if not instance_list: return None # type: ignore - return instance_list[0] + raise MultipleObjectsReturned("Multiple objects returned, expected exactly one") return instance_list