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

Generate proper type for `nullable` but required fields

Open shreyas44 opened this issue 4 years ago • 1 comments
trafficstars

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:

  1. The field is nullable but required
  2. While generating the json schema from the model, nullable isn't in the output

Describe the solution you'd like

  1. To make sure the nullable property is in the output schema, we can add nullable=True as an argument to Field
class Foo(BaseModel):
  a: Optional[str] = Field(nullable=True)
  1. 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 avatar Sep 23 '21 16:09 shreyas44

@shreyas44 I'm sorry for my response late.

  1. 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)
  1. 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.

koxudaxi avatar Sep 30 '21 14:09 koxudaxi