Skip to content

Commit

Permalink
Pass FieldInfo straight through to create_model() if no need to c…
Browse files Browse the repository at this point in the history
…hange.

Where a field is neither excluded, nor mapped the least surprising thing would be that the field stays the same.
  • Loading branch information
peterschutt committed May 24, 2022
1 parent 39d2ffd commit 2e5b1f6
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 2e5b1f6

Please sign in to comment.