simplify adding relations

This commit is contained in:
collerek
2020-08-11 17:47:06 +02:00
parent 867fc691f7
commit 7083b50712
4 changed files with 41 additions and 37 deletions

BIN
.coverage

Binary file not shown.

View File

@ -1,4 +1,4 @@
from typing import Type, List, Any, Union, TYPE_CHECKING
from typing import Type, List, Any, Union, TYPE_CHECKING, Optional
import sqlalchemy
from pydantic import BaseModel
@ -12,9 +12,8 @@ if TYPE_CHECKING: # pragma no cover
def create_dummy_instance(fk: Type["Model"], pk: int = None) -> "Model":
init_dict = {fk.__pkname__: pk or -1}
init_dict = {
**init_dict,
**{fk.__pkname__: pk or -1},
**{
k: create_dummy_instance(v.to)
for k, v in fk.__model_fields__.items()
@ -52,7 +51,10 @@ class ForeignKey(BaseField):
def expand_relationship(
self, value: Any, child: "Model"
) -> Union["Model", List["Model"]]:
) -> Optional[Union["Model", List["Model"]]]:
if value is None:
return None
if isinstance(value, orm.models.Model) and not isinstance(value, self.to):
raise RelationshipInstanceError(
@ -77,15 +79,10 @@ class ForeignKey(BaseField):
)
model = create_dummy_instance(fk=self.to, pk=value)
self.add_to_relationship_registry(model, child)
return model
def add_to_relationship_registry(self, model: "Model", child: "Model") -> None:
model._orm_relationship_manager.add_relation(
model.__class__.__name__.lower(),
child.__class__.__name__.lower(),
model,
child,
virtual=self.virtual,
)
return model

View File

@ -57,14 +57,14 @@ class RelationshipManager:
def add_relation(
self,
parent_name: str,
child_name: str,
parent: "FakePydantic",
child: "FakePydantic",
virtual: bool = False,
) -> None:
parent_id = parent._orm_id
child_id = child._orm_id
parent_name = parent.get_name()
child_name = child.get_name()
if virtual:
child_name, parent_name = parent_name, child_name
child_id, parent_id = parent_id, child_id

View File

@ -74,6 +74,13 @@ async def test_wrong_query_foreign_key_type():
Track(title="The Error", album="wrong_pk_type")
@pytest.mark.asyncio
async def test_setting_explicitly_empty_relation():
async with database:
track = Track(album=None, title="The Bird", position=1)
assert track.album is None
@pytest.mark.asyncio
async def test_model_crud():
async with database: