Skip to content

Commit

Permalink
Make it work to use $ref as an alias (#6568)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed Jul 12, 2023
1 parent 1e50b0d commit ed0171c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
9 changes: 6 additions & 3 deletions pydantic/json_schema.py
Expand Up @@ -191,8 +191,8 @@ def remap_json_schema(self, schema: Any) -> Any:
return [self.remap_json_schema(item) for item in schema]
elif isinstance(schema, dict):
for key, value in schema.items():
if key == '$ref':
schema['$ref'] = self.remap_json_ref(JsonRef(schema['$ref']))
if key == '$ref' and isinstance(value, str):
schema['$ref'] = self.remap_json_ref(JsonRef(value))
elif key == '$defs':
schema['$defs'] = {
self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value)
Expand Down Expand Up @@ -1959,6 +1959,8 @@ def _add_json_refs(schema: Any) -> None:
if isinstance(schema, dict):
if '$ref' in schema:
json_ref = JsonRef(schema['$ref'])
if not isinstance(json_ref, str):
return # in this case, '$ref' might have been the name of a property
already_visited = json_ref in json_refs
json_refs[json_ref] += 1
if already_visited:
Expand Down Expand Up @@ -2213,7 +2215,8 @@ def _get_all_json_refs(item: Any) -> set[JsonRef]:
refs: set[JsonRef] = set()
if isinstance(item, dict):
for key, value in item.items():
if key == '$ref':
if key == '$ref' and isinstance(value, str):
# the isinstance check ensures that '$ref' isn't the name of a property, etc.
refs.add(JsonRef(value))
elif isinstance(value, dict):
refs.update(_get_all_json_refs(value))
Expand Down
12 changes: 12 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -5060,3 +5060,15 @@ class Bar(BaseModel):
'title': 'Foo',
'type': 'object',
}


def test_dollar_ref_alias():
class MyModel(BaseModel):
my_field: str = Field(alias='$ref')

assert MyModel.model_json_schema() == {
'properties': {'$ref': {'title': '$Ref', 'type': 'string'}},
'required': ['$ref'],
'title': 'MyModel',
'type': 'object',
}

0 comments on commit ed0171c

Please sign in to comment.