Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: set default to None for pydantic generator #1663

Merged
merged 2 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
exports[`Should be able to render python models and should log expected output to console: class-model 1`] = `
Array [
"class Root(BaseModel):
optionalField: Optional[str] = Field(alias='''this field is optional''')
optionalField: Optional[str] = Field(alias='''this field is optional''', default=None)
requiredField: str = Field(alias='''this field is required''')
noDescription: Optional[str] = Field()
options: Optional[Options] = Field()
noDescription: Optional[str] = Field(default=None)
options: Optional[Options] = Field(default=None)
",
]
`;
Expand Down
18 changes: 11 additions & 7 deletions src/generators/python/presets/Pydantic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ const PYTHON_PYDANTIC_CLASS_PRESET: ClassPresetType<PythonOptions> = {
);
},
property(params) {
const type = params.property.required
? params.property.property.type
: `Optional[${params.property.property.type}]`;
const alias = params.property.property.originalInput['description']
? `alias='''${params.property.property.originalInput['description']}'''`
: '';
const { propertyName, required, property } = params.property;
const type = required ? property.type : `Optional[${property.type}]`;
const description = property.originalInput['description'];
const alias = description ? `alias='''${description}'''` : '';
const defaultValue = required ? '' : 'default=None';

return `${params.property.propertyName}: ${type} = Field(${alias})`;
if (alias && defaultValue) {
return `${propertyName}: ${type} = Field(${alias}, ${defaultValue})`;
} else if (alias) {
return `${propertyName}: ${type} = Field(${alias})`;
}
return `${propertyName}: ${type} = Field(${defaultValue})`;
},
ctor: () => '',
getter: () => '',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ exports[`PYTHON_PYDANTIC_PRESET should render pydantic for class 1`] = `
prop: Optional[str] = Field(alias='''test
multi
line
description''')
additionalProperties: Optional[dict[Any, Any]] = Field()
description''', default=None)
additionalProperties: Optional[dict[Any, Any]] = Field(default=None)
"
`;
Loading