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

Fix schema sorting bug with default values #7817

Merged
merged 1 commit into from Oct 13, 2023
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
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