Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default to JSON schema when const is True #4152

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/4031-aminalaee.md
@@ -0,0 +1 @@
Add `default` value in JSON Schema when `const=True`
7 changes: 1 addition & 6 deletions pydantic/schema.py
Expand Up @@ -210,12 +210,7 @@ def get_field_info_schema(field: ModelField, schema_overrides: bool = False) ->
schema_['description'] = field.field_info.description
schema_overrides = True

if (
not field.required
and not field.field_info.const
and field.default is not None
and not is_callable_type(field.outer_type_)
):
if not field.required and field.default is not None and not is_callable_type(field.outer_type_):
schema_['default'] = encode_default(field.default)
schema_overrides = True

Expand Down
2 changes: 2 additions & 0 deletions tests/test_main.py
Expand Up @@ -585,12 +585,14 @@ class Model(BaseModel):
'properties': {
'a': {
'const': [SubModel(b=1), SubModel(b=2), SubModel(b=3)],
'default': [{'b': 1}, {'b': 2}, {'b': 3}],
'items': {'$ref': '#/definitions/SubModel'},
'title': 'A',
'type': 'array',
},
'b': {
'const': [{'b': 4}, {'b': 5}, {'b': 6}],
'default': [{'b': 4}, {'b': 5}, {'b': 6}],
'items': {'$ref': '#/definitions/SubModel'},
'title': 'B',
'type': 'array',
Expand Down
2 changes: 1 addition & 1 deletion tests/test_schema.py
Expand Up @@ -549,7 +549,7 @@ class Model(BaseModel):
assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string', 'const': 'some string'}},
'properties': {'a': {'title': 'A', 'type': 'string', 'const': 'some string', 'default': 'some string'}},
}


Expand Down