Skip to content

Differentiate "required with default", "required nullable", and "optional" properties #437

Description

@amh4r

⚠️ I'm willing to work on this change myself. But before starting, I'd like to discuss it.

Is your feature request related to a problem? Please describe.

Here's a repro: https://github.com/goodoldneon/datamodel-code-generator-Repro

OpenAPI allows you to specify properties as:

  • Required
  • Required with default
  • Required nullable
  • Unrequired

However, mashalling the pydantic models (e.g. BaseModel.dict()) will not differentiate them.

For example, let's say we have the following OpenAPI schema:

Foo:
  type: object
  properties:
    required:
      type: integer
    required_default:
      type: integer
      default: 2
    required_nullable:
      type: integer
      nullable: true
    unrequired:
      type: integer
  required:
    - required
    - required_default
    - required_nullable

If I marshall the generated model into JSON, I expect that all of the required* properties will always exist but the unrequired property may not.

If I instantiate Foo like this:

Foo(required=1, required_nullable=None)

Then I'd expect the marshalled JSON to be:

{
  "required": 1,
  "required_default": 2,
  "required_nullable": null,
}

But that doesn't seem to be possible.

Describe the solution you'd like

I thought I could do this with a new BaseModel.dict() argument, but the maintainers of pydantic rejected my PR:

pydantic/pydantic#2837

They provided a (seemingly) good solution to the problem on their end. This makes me think the solution for datamodel-code-generator would be a new CLI arg that creates models like @PrettyWood's example.

Describe alternatives you've considered

I considered making a change to pydantic but my PR was rejected.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions