Skip to content

Import statement missing if $ref to an array in sibling directory and using --collapse-root-models #2522

@Raekkeri

Description

@Raekkeri

Describe the bug
Import statement for model generated from referenced JSON schema file are not generated when $ref is located in sibling directory, is an array and tool is used with --collapse-root-models flag.

To Reproduce

Example schema (the main schema), located in "example/example.schema.json"

{
  "$id": "example/example.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Example",
  "description": "Example schema",
  "type": "object",
  "properties": {
    "somerefs": {
      "$ref": "../someref/somerefs.schema.json"
    }
  },
  "required": ["somerefs"]
}

"someref/somerefs.schema.json":

{
  "$id": "someref/somerefs.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "SomeRefs",
  "type": "array",
  "items": {
    "$ref": "someref.schema.json"
  }
}

"someref/someref.schema.json":

{
  "$id": "someref/someref.schema.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Some Ref",
  "description": "Schema for some ref",
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Unique identifier for the equation"
    }
  },
  "required": ["id"]
}

Used commandline:

$ datamodel-codegen --url http://localhost:8888/example/example.schema.json --output Example --input-file-type jsonschema --output-model-type pydantic_v2.BaseModel --extra-fields ignore --collapse-root-models


# Then:

$ python -c "from Example import Example;Example()"

What happens
There is an error message saying "pydantic.errors.PydanticUserError: Example is not fully defined; you should define someref, then call Example.model_rebuild()."

In the Example/__init__.py file, there is no import for someref.Schema.

Expected behavior
Example would be usable.

Version:

  • OS: macOS
  • Python version: Python 3.10.4
  • datamodel-code-generator version: 0.35.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions