Skip to content

Commit

Permalink
Merge pull request #116 from peterschutt/issue-115
Browse files Browse the repository at this point in the history
Pass `FieldInfo` straight through to `create_model()` if no need to change
  • Loading branch information
Goldziher authored May 25, 2022
2 parents 39d2ffd + 2e5b1f6 commit c963709
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
14 changes: 9 additions & 5 deletions starlite/dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,16 @@ def create_obj(data: MyClassDTO) -> MyClass:
field_name, field_type = mapping
else:
field_name = mapping
if model_field.field_info.default not in (Undefined, None, ...):
field_definitions[field_name] = (field_type, model_field.default)
elif model_field.required or not model_field.allow_none:
field_definitions[field_name] = (field_type, ...)
if model_field.field_info.default not in (Undefined, None, ...):
field_definitions[field_name] = (field_type, model_field.default)
elif model_field.required or not model_field.allow_none:
field_definitions[field_name] = (field_type, ...)
else:
field_definitions[field_name] = (field_type, None)
else:
field_definitions[field_name] = (field_type, None)
# prevents losing Optional
field_type = Optional[field_type] if model_field.allow_none else field_type
field_definitions[field_name] = (field_type, model_field.field_info)
dto = cast(Type[DTO[T]], create_model(name, __base__=DTO, **field_definitions)) # type: ignore
dto.dto_source_model = source
dto.dto_source_plugin = plugin
Expand Down
5 changes: 5 additions & 0 deletions tests/test_dto_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,8 @@ def test_dto_factory_preserves_field_allow_none_false() -> None:
assert Example.__fields__["password"].allow_none is False
ExampleDTO = DTOFactory()("ExampleDTO", Example)
assert ExampleDTO.__fields__["password"].allow_none is False


def test_dto_factory_preserves_field_info_where_unnecessary_to_change() -> None:
ExampleDTO = DTOFactory(plugins=[])("ExampleDTO", PydanticPet, exclude=[], field_mapping={}, field_definitions={})
assert PydanticPet.__fields__["name"].field_info is ExampleDTO.__fields__["name"].field_info

0 comments on commit c963709

Please sign in to comment.