-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Initial Checks
- I have searched Google & GitHub for similar requests and couldn't find anything
- I have read and followed the docs and still think this feature is missing
Description
I am using Pydantic 2.6.4 to generate JSON schemas for web forms, using React as the front-end framework. I would like to write a field in a Pydantic model that has no default value but is not included in the "required" list in the translated JSON schema.
Consider the following schema:
{
"title": "Cell",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string"
},
"organism": {
"type": "string"
}
},
"required": ["name", "type"]
}
The property "organism" has no default value, and is not "required". It seems impossible to write a Pydantic model that will translate to the above schema. If you have no default value in Pydantic, it will be required in JSON and vice versa. Translating the above schema to Pydantic using datamodel-code-generator gives:
class Cell(BaseModel):
name: str
type: str
organism: Optional[str] = None
But if I were to have written that in Pydantic originally, that is translated by Pydantic into JSON schema as:
"organism": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
],
"default": null,
"title": "Organism"
Using the above schema on a webform on the front-end with React results in a drop-down menu for the two types, and not an empty box that the user can choose not to enter anything into and which will not be included in the form data, which is what I want.
Affected Components
- Compatibility between releases
- Data validation/parsing
- Data serialization -
.model_dump()
and.model_dump_json()
- JSON Schema
- Dataclasses
- Model Config
- Field Types - adding or changing a particular data type
- Function validation decorator
- Generic Models
- Other Model behaviour -
model_construct()
, pickling, private attributes, ORM mode - Plugins and integration with other tools - mypy, FastAPI, python-devtools, Hypothesis, VS Code, PyCharm, etc.