Skip to content

Commit

Permalink
fix: set default to None for optional fields
Browse files Browse the repository at this point in the history
- Fix in Pydantic Python Generator for optional values.
- default=None should be added in `Field()` if the property is optional.

Signed-off-by: Harshil Jani <harshiljani2002@gmail.com>
  • Loading branch information
Harshil-Jani committed Dec 15, 2023
1 parent 7f7c3b3 commit b2c7706
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/generators/python/presets/Pydantic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,20 @@ 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']}'''`
: '';

return `${params.property.propertyName}: ${type} = Field(${alias})`;
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 (
alias && defaultValue
? `${propertyName}: ${type} = Field(${alias}, ${defaultValue})`
: alias
? `${propertyName}: ${type} = Field(${alias})`
: defaultValue
? `${propertyName}: ${type} = Field(${defaultValue})`
: ''
);
},
ctor: () => '',
getter: () => '',
Expand Down

0 comments on commit b2c7706

Please sign in to comment.