From 762ac1b7257be5b30e2c133f9601a88f95520a32 Mon Sep 17 00:00:00 2001 From: Florian Ludwig Date: Thu, 11 Jun 2020 11:56:11 +0200 Subject: [PATCH] dynamic field serialization (#141) * dynamic field serialization * run black --- datamodel_code_generator/model/base.py | 6 +++++- .../model/pydantic/base_model.py | 20 ++++++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/datamodel_code_generator/model/base.py b/datamodel_code_generator/model/base.py index 2a49c554d..a818fe053 100644 --- a/datamodel_code_generator/model/base.py +++ b/datamodel_code_generator/model/base.py @@ -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]: diff --git a/datamodel_code_generator/model/pydantic/base_model.py b/datamodel_code_generator/model/pydantic/base_model.py index 5e4dca8e4..7522b7c00 100644 --- a/datamodel_code_generator/model/pydantic/base_model.py +++ b/datamodel_code_generator/model/pydantic/base_model.py @@ -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): @@ -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):