datamodel-code-generator
datamodel-code-generator copied to clipboard
Default value when using ref
Hello!
I have spec which uses ref. I would like to have default value for referenced field to be generated automatically. The only default value I managed to get is None.
My spec is like this:
...
components:
schemas:
ParameterSet:
type: object
properties:
parameters:
$ref: '#/components/schemas/Parameters'
# default:
# fraction: 99
Parameters:
type: object
properties:
fraction: {default: 0.75, type: number}
...
Generated code is:
class ParameterSet(BaseModel):
parameters: Optional[Parameters] = None
If I uncomment default section I get this, which is not correct as I understand:
class ParameterSet(BaseModel):
parameters: Optional[Parameters] = {'fraction': 99}
I would like to get something like this:
class ParameterSet(BaseModel):
parameters: Optional[Parameters] = Field(default_factory=lambda: Parameters(fraction = 99))
I run generator like this:
python3 -m datamodel_code_generator --input specs/spec.yml --output src/generated/models.py --use-subclass-enum --use-default --set-default-enum-member --output-model-type pydantic_v2.BaseModel --strip-default-none --field-constraints --field-include-all-keys
Is there a way to achieve this? Maybe there are some arguments I missed?
datamodel-code-generator version is 0.25.1.
Thanks!
I ran into the same problem, and I was able to get the default factory to work using the pydantic v1 generator instead. I am not completely sure if that was the only change though because I am jumping between 2 divergent branches on my complex build chain, so sorry if that's not right.
This should be fixed in 0.25.4.