Skip to content

Commit ba30bdc

Browse files
committed
Improve aliases for Pydantic models
The pydantic models generated include field aliases for fields that use camel case as opposed to snake case (customary in Python). The alias definitions are compatible with python's builtin dataclasses and are correctly detected by LSPs, however in the same models the `populate_by_name` option is set to True. This option allows the instantiotion using the actual field names (snake case) instead of the defined alias (camcel case). This options is not correctly recognized by most LSP and therefore results in two warnings per field. The first warning states that hte snake case version of the field is not a valid argument, and the second warning states that the camcel case version of the argument is missing. Exampel: ```python class WebSessionInfo(BaseModel): model_config = { "populate_by_name": True, } session_id: str = Field(alias="sessionID") ``` The above model can be instantiated like so: `WebSessionInfo(session_id='abc')`, however this results in two warnings (`session_id` is not a valid argument, and `sessionID` is missing). Settings `validation_alias` and `serialization_alias` results in the exact same behavior as far as validation and serialization are concerned, however they are not standard dataclass options and are therefore not recognized by LSPs. This removes the warnings.
1 parent e7287d1 commit ba30bdc

1 file changed

Lines changed: 2 additions & 1 deletion

File tree

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonPydanticV1Codegen.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -908,7 +908,8 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) {
908908

909909
// field
910910
if (cp.baseName != null && !cp.baseName.equals(cp.name)) { // base name not the same as name
911-
fields.add(String.format(Locale.ROOT, "alias=\"%s\"", cp.baseName));
911+
fields.add(String.format(Locale.ROOT, "validation_alias=\"%s\"", cp.baseName));
912+
fields.add(String.format(Locale.ROOT, "serialization_alias=\"%s\"", cp.baseName));
912913
}
913914

914915
if (!StringUtils.isEmpty(cp.description)) { // has description

0 commit comments

Comments
 (0)