datamodel-code-generator
datamodel-code-generator copied to clipboard
Generate proper type for `nullable` but required fields
Is your feature request related to a problem? Please describe.
Currently if nullable is set to True in the schema definition, the generated type is an Optional. Though this isn't wrong, there are still 2 things that aren't covered:
- The field is nullable but required
- While generating the json schema from the model,
nullableisn't in the output
Describe the solution you'd like
- To make sure the nullable property is in the output schema, we can add
nullable=Trueas an argument toField
class Foo(BaseModel):
a: Optional[str] = Field(nullable=True)
- For required nullable fields, the below solution works
class Foo(BaseModel):
a: Optional[str] = Field(..., nullable=True)
Passing ... as the first argument to Field marks the field as required and an error is raised if we don't pass a value for a. And, since the type of the field is Optional[str] it means we can still pass None as a valid value.
@shreyas44 I'm sorry for my response late.
- The field is nullable but required
You can use --strict-nullable option to get Optional[str] = Field(...)
--strict-nullable Treat default field as a non-nullable field (Only OpenAPI)
- While generating the json schema from the model, nullable isn't in the output
I don't know any idea. If you need the result then I must change --field-extra-keys option.
The option passes extra keys. But, nullable is ignored now.