Describe the bug
If I have a jsonschema file that references another jsonschema file with a circular dependency, the pydantic model file that is produced has the classes out-of-order so the file is invalid.
To Reproduce
Example schema:
wrapper.json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$ref": "./staff.json"
}
staff.json
{
"title": "staff",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"location": {
"$ref": "./location.json"
}
},
"type": "object"
}
location.json
{
"title": "location",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"staff": {
"$ref": "./staff.json"
}
},
"type": "object"
}
Used commandline:
datamodel-codegen --output-model-type pydantic_v2.BaseModel \
--input wrapper.json \
--input-file-type jsonschema \
--output ./staff.py
Expected behavior
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, RootModel
class Staff(BaseModel):
location: Optional[Location] = None
class Location(BaseModel):
staff: Optional[Staff] = None
class Model(RootModel[Staff]):
root: Staff
Model.model_rebuild()
Staff.model_rebuild()
Version:
Additional context
The pydantic file that is produced has the class declaration out-of-order, so I get a NameError: name 'Staff' is not defined
error when trying to import from it. The output for the scenario above is:
from __future__ import annotations
from typing import Optional
from pydantic import BaseModel, RootModel
# Staff is referenced here before it is defined, this class needs to be moved lower in the file
class Model(RootModel[Staff]):
root: Staff
class Staff(BaseModel):
location: Optional[Location] = None
class Location(BaseModel):
staff: Optional[Staff] = None
Model.model_rebuild()
Staff.model_rebuild()
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too