datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Default value when using ref

Open aldoshkind opened this issue 1 year ago • 3 comments
trafficstars

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!

aldoshkind avatar Jan 06 '24 05:01 aldoshkind

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.

jbezuk avatar Feb 08 '24 15:02 jbezuk

This should be fixed in 0.25.4.

jamesbezuk avatar Feb 14 '24 06:02 jamesbezuk