Skip to content

Commit

Permalink
Add default to JSON schema when const is True (#4152)
Browse files Browse the repository at this point in the history
  • Loading branch information
aminalaee committed Aug 8, 2022
1 parent 42462ab commit 8f388e1
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 7 deletions.
1 change: 1 addition & 0 deletions changes/4031-aminalaee.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `default` value in JSON Schema when `const=True`
7 changes: 1 addition & 6 deletions pydantic/schema.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
Expand Up @@ -586,12 +586,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
Original file line number Diff line number Diff line change
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

0 comments on commit 8f388e1

Please sign in to comment.