Skip to content

Commit

Permalink
Fix schema sorting bug with default values (#7817)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Oct 13, 2023
1 parent 3dac743 commit 2ace8cb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
4 changes: 2 additions & 2 deletions pydantic/json_schema.py
Expand Up @@ -2224,15 +2224,15 @@ def _sort_json_schema(value: JsonSchemaValue, parent_key: str | None = None) ->
if isinstance(value, dict):
sorted_dict: dict[str, JsonSchemaValue] = {}
keys = value.keys()
if parent_key != 'properties':
if (parent_key != 'properties') and (parent_key != 'default'):
keys = sorted(keys)
for key in keys:
sorted_dict[key] = _sort_json_schema(value[key], parent_key=key)
return sorted_dict
elif isinstance(value, list):
sorted_list: list[JsonSchemaValue] = []
for item in value: # type: ignore
sorted_list.append(_sort_json_schema(item))
sorted_list.append(_sort_json_schema(item, parent_key))
return sorted_list # type: ignore
else:
return value
Expand Down
12 changes: 9 additions & 3 deletions tests/test_json_schema.py
Expand Up @@ -5260,7 +5260,7 @@ class Model(BaseModel):
a: str

class OuterModel(BaseModel):
inner: List[Model]
inner: List[Model] = Field(default=[Model(b=1, a='fruit')])

# verify the schema contents
# this is just to get a nicer error message / diff if it fails
Expand All @@ -5273,8 +5273,14 @@ class OuterModel(BaseModel):
'type': 'object',
}
},
'properties': {'inner': {'items': {'$ref': '#/$defs/Model'}, 'title': 'Inner', 'type': 'array'}},
'required': ['inner'],
'properties': {
'inner': {
'default': [{'b': 1, 'a': 'fruit'}],
'items': {'$ref': '#/$defs/Model'},
'title': 'Inner',
'type': 'array',
}
},
'title': 'OuterModel',
'type': 'object',
}
Expand Down

0 comments on commit 2ace8cb

Please sign in to comment.