Skip to content

Commit

Permalink
xx_or_create add fetch_related arg
Browse files Browse the repository at this point in the history
  • Loading branch information
CMHopeSunshine committed Sep 16, 2023
1 parent 3332a77 commit 6c608e7
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
13 changes: 11 additions & 2 deletions cherry/models/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Tuple,
Type,
TYPE_CHECKING,
Union,
)
from typing_extensions import dataclass_transform, Self

Expand All @@ -27,7 +28,6 @@
)
from cherry.fields.types import get_sqlalchemy_type_from_field
from cherry.fields.utils import (
args_and_kwargs_to_clause_list,
classproperty,
)
from cherry.meta.meta import init_meta_config, MetaConfig, mix_meta_config
Expand Down Expand Up @@ -553,10 +553,15 @@ async def get_or_create(
cls,
*args: Any,
defaults: Optional[DictStrAny] = None,
fetch_related: Union[bool, Tuple[Any, ...]] = False,
**kwargs: Any,
) -> Tuple[Self, bool]:
"""select one model with filter condition, if not exist, create one"""
queryset = cls.filter(*args, **kwargs)
if fetch_related is True or isinstance(fetch_related, tuple):
queryset = queryset.prefetch_related(
() if fetch_related is True else fetch_related,
)
try:
return await queryset.get(), True
except NoMatchDataError:
Expand All @@ -574,12 +579,16 @@ async def update_or_create(
cls,
*args: Any,
defaults: Optional[DictStrAny] = None,
fetch_related: Union[bool, Tuple[Any, ...]] = False,
**kwargs: Any,
) -> Tuple[Self, bool]:
"""update one model with filter condition,
if not exist, create one with filter and defaults values"""
clause_list = args_and_kwargs_to_clause_list(cls, args, kwargs)
queryset = cls.filter(*args, **kwargs)
if fetch_related is True or isinstance(fetch_related, tuple):
queryset = queryset.prefetch_related(
() if fetch_related is True else fetch_related,
)
try:
model = await queryset.get()
return await model.update(**(defaults or {})), True
Expand Down
4 changes: 2 additions & 2 deletions cherry/queryset/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ async def _fetch_one_related(self, conn: AsyncConnection, now_data: Dict[str, An
rfield.related_model.__meta__.table.select().where(
getattr(
rfield.related_model,
rfield.related_field_name,
rfield.related_field.foreign_key_self_name,
)
== now_data[target_field.foreign_key],
),
Expand Down Expand Up @@ -405,7 +405,7 @@ async def _fetch_many_related(
rfield.related_model.__meta__.table.select().where(
getattr(
rfield.related_model,
rfield.related_field_name,
rfield.related_field.foreign_key_self_name,
).in_(related_values),
),
)
Expand Down
5 changes: 5 additions & 0 deletions tests/test_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,8 @@ async def test_query_with_one_to_many():
assert len(school1.students) == 0
await school2.fetch_related(School.students)
assert len(school2.students) == 1

schools = await School.select_related().all()
assert len(schools) == 2
assert len(schools[0].students) == 0
assert len(schools[1].students) == 1

0 comments on commit 6c608e7

Please sign in to comment.