Skip to content

Commit

Permalink
fix: added getitem method to relation proxy model
Browse files Browse the repository at this point in the history
  • Loading branch information
SepehrBazyar committed Aug 27, 2022
1 parent 7330d56 commit 0663fb3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
25 changes: 22 additions & 3 deletions ormar/relations/relation_proxy.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
from typing import Any, Generic, List, Optional, TYPE_CHECKING, Type, TypeVar
from typing import (
Any,
Generic,
List,
Optional,
TYPE_CHECKING,
Type,
TypeVar,
Union,
)

import ormar
from ormar.exceptions import NoMatch, RelationshipInstanceError
Expand Down Expand Up @@ -52,8 +61,18 @@ def related_field_name(self) -> str:

return self._related_field_name

def __getitem__(self, item: Any) -> "T": # type: ignore
return super().__getitem__(item)
def __getitem__(self, key: Union[int, slice]) -> "QuerysetProxy[T]":
"""
You can slice the results to desired number of parent models.
Actual call delegated to QuerySet.
:param key: numbers of models to slicing
:type key: int | slice
:return: QuerysetProxy
:rtype: QuerysetProxy
"""
return self.queryset_proxy[key]

def __getattribute__(self, item: str) -> Any:
"""
Expand Down
22 changes: 11 additions & 11 deletions tests/test_queries/test_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,16 +180,16 @@ async def test_slice_getitem_queryset_on_proxy():
c = await Car(name=f"{i}").save()
await user.cars.add(c)

cars_page1 = user.cars[:5]
assert len(cars_page1) == 5
assert cars_page1[0].name == "0"
assert cars_page1[4].name == "4"
await user.cars[:5].all()
assert len(user.cars) == 5
assert user.cars[0].name == "0"
assert user.cars[4].name == "4"

cars_page2 = user.cars[5:10]
assert len(cars_page2) == 5
assert cars_page2[0].name == "5"
assert cars_page2[4].name == "9"
await user.cars[5:10].all()
assert len(user.cars) == 5
assert user.cars[0].name == "5"
assert user.cars[4].name == "9"

cars_page3 = user.cars[10:]
assert len(cars_page3) == 10
assert cars_page3[0].name == "10"
await user.cars[10:].all()
assert len(user.cars) == 10
assert user.cars[0].name == "10"

0 comments on commit 0663fb3

Please sign in to comment.