fix nested dicts, add more real life fastapi tests

This commit is contained in:
collerek
2020-08-15 12:37:48 +02:00
parent 3232c99fca
commit a0ad85811b
9 changed files with 161 additions and 26 deletions

View File

@ -117,15 +117,19 @@ class FakePydantic(list, metaclass=ModelMetaclass):
def pk_type(cls) -> Any:
return cls.__model_fields__[cls.__pkname__].__type__
def dict(self) -> Dict: # noqa: A003
def dict(self, nested=False) -> Dict: # noqa: A003
dict_instance = self.values.dict()
for field in self._extract_related_names():
nested_model = getattr(self, field)
if isinstance(nested_model, list):
dict_instance[field] = [x.dict() for x in nested_model]
if self.__model_fields__[field].virtual and nested:
continue
if isinstance(nested_model, list) and not isinstance(
nested_model, ormar.Model
):
dict_instance[field] = [x.dict(nested=True) for x in nested_model]
else:
dict_instance[field] = (
nested_model.dict() if nested_model is not None else {}
nested_model.dict(nested=True) if nested_model is not None else {}
)
return dict_instance

View File

@ -55,7 +55,7 @@ class Model(FakePydantic):
def pk(self, value: Any) -> None:
setattr(self.values, self.__pkname__, value)
async def save(self) -> int:
async def save(self) -> "Model":
self_fields = self._extract_model_db_fields()
if self.__model_fields__.get(self.__pkname__).autoincrement:
self_fields.pop(self.__pkname__, None)
@ -63,7 +63,7 @@ class Model(FakePydantic):
expr = expr.values(**self_fields)
item_id = await self.__database__.execute(expr)
self.pk = item_id
return item_id
return self
async def update(self, **kwargs: Any) -> int:
if kwargs:

View File

@ -160,10 +160,15 @@ class QuerySet:
# substitute related models with their pk
for field in self.model_cls._extract_related_names():
if field in new_kwargs and new_kwargs.get(field) is not None:
new_kwargs[field] = getattr(
new_kwargs.get(field),
self.model_cls.__model_fields__[field].to.__pkname__,
)
if isinstance(new_kwargs.get(field), ormar.Model):
new_kwargs[field] = getattr(
new_kwargs.get(field),
self.model_cls.__model_fields__[field].to.__pkname__,
)
else:
new_kwargs[field] = new_kwargs.get(field).get(
self.model_cls.__model_fields__[field].to.__pkname__
)
# Build the insert expression.
expr = self.table.insert()