Skip to content

Commit

Permalink
Cache the relation map dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
marpulli committed May 3, 2023
1 parent bcc3af0 commit aa0dbe3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions ormar/models/helpers/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def populate_default_options_values( # noqa: CCR001
}

new_model.__relation_map__ = None
new_model.__relation_map_dict__ = None


class Connection(sqlite3.Connection):
Expand Down
13 changes: 12 additions & 1 deletion ormar/models/newbasemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ class NewBaseModel(pydantic.BaseModel, ModelTableProxy, metaclass=ModelMetaclass
__metadata__: sqlalchemy.MetaData
__database__: databases.Database
__relation_map__: Optional[List[str]]
__relation_map_dict__: Optional[dict[str, Any]]
__cached_hash__: Optional[int]
_orm_relationship_manager: AliasManager
_orm: RelationsManager
Expand Down Expand Up @@ -734,6 +735,16 @@ def _extract_nested_models( # noqa: CCR001, CFQ002
except ReferenceError:
dict_instance[field] = None
return dict_instance


@classmethod
def _related_models_dict(cls) -> dict:
if not cls.__relation_map_dict__:
cls.__relation_map_dict__ = translate_list_to_dict(
cls._iterate_related_models()
)
return cls.__relation_map_dict__


def dict( # type: ignore # noqa A003
self,
Expand Down Expand Up @@ -813,7 +824,7 @@ def dict( # type: ignore # noqa A003
relation_map = (
relation_map
if relation_map is not None
else translate_list_to_dict(self._iterate_related_models())
else self._related_models_dict()
)
pk_only = getattr(self, "__pk_only__", False)
if relation_map and not pk_only:
Expand Down

0 comments on commit aa0dbe3

Please sign in to comment.