Skip to content

Commit

Permalink
Modify get_or_none to raise MultipleObjectsReturned error (#298)
Browse files Browse the repository at this point in the history
  • Loading branch information
hqsz authored Feb 25, 2020
1 parent 7946792 commit bea64a9
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
8 changes: 4 additions & 4 deletions tests/test_queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
8 changes: 5 additions & 3 deletions tortoise/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down

0 comments on commit bea64a9

Please sign in to comment.