Skip to content

Commit

Permalink
dynamic field serialization (#141)
Browse files Browse the repository at this point in the history
* dynamic field serialization

* run black
  • Loading branch information
FlorianLudwig authored Jun 11, 2020
1 parent cdb14fe commit 762ac1b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
6 changes: 5 additions & 1 deletion datamodel_code_generator/model/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@ class DataModelFieldBase(BaseModel):
imports: List[Import] = []
type_hint: Optional[str] = None
unresolved_types: List[str] = []
field: Optional[str]

@property
def field(self) -> Optional[str]:
"""for backwards compatibility"""
return None

@optional
def _get_type_hint(self) -> Optional[str]:
Expand Down
20 changes: 17 additions & 3 deletions datamodel_code_generator/model/pydantic/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

class DataModelField(DataModelFieldBase):
_FIELDS_KEYS: Set[str] = {'alias', 'example', 'examples', 'description', 'title'}
field: Optional[str] = None

def get_valid_argument(self, value: Any) -> Union[str, List[Any], Dict[Any, Any]]:
if isinstance(value, str):
Expand All @@ -25,13 +24,28 @@ def get_valid_argument(self, value: Any) -> Union[str, List[Any], Dict[Any, Any]

def __init__(self, **values: Any) -> None:
super().__init__(**values)

@property
def field(self) -> Optional[str]:
"""for backwards compatibility"""
result = str(self)
if result == "":
return None

return result

def __str__(self) -> str:
field_arguments = [
f"{k}={self.get_valid_argument(v)}"
for k, v in self.dict(include=self._FIELDS_KEYS).items()
if v is not None
]
if field_arguments:
self.field = f'Field({"..." if self.required else self.get_valid_argument(self.default)}, {",".join(field_arguments)})'
if not field_arguments:
return ""

value_arg = "..." if self.required else self.get_valid_argument(self.default)
kwargs = ",".join(field_arguments)
return f'Field({value_arg}, {kwargs})'


class BaseModel(DataModel):
Expand Down

0 comments on commit 762ac1b

Please sign in to comment.