Differentiate "required with default", "required nullable", and "optional" properties
See original GitHub issue⚠️ 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:
https://github.com/samuelcolvin/pydantic/discussions/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.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:12 (11 by maintainers)
Top GitHub Comments
Sounds good! I’ll work on it this week
@koxudaxi sorry I’ve slept on this for so long. I decided to give it another shot in #670. There’s still some work left, but I was hoping to get some feedback from you on what I have so far. Thanks for taking a look when you get the chance!