Datamodel-code-generator: Missing __root__ type for additionalProperties model

Created on 21 Jan 2021  路  3Comments  路  Source: koxudaxi/datamodel-code-generator

Describe the bug
When json schema includes an object with additionalProperties , the generated pydantic model doesn't contain __root__ attribute

To Reproduce

Example schema:


{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "test.json",
  "description": "test",
  "type": "object",
  "required": [
    "test_id",
    "test_ip",
    "result"
  ],
  "properties": {
    "test_id": {
      "type": "string",
      "description": "test ID"
    },
    "test_ip": {
      "type": "string",
      "description": "test IP"
    },
    "result": {
      "type": "object",
      "additionalProperties": {
        "type": "integer"
      }
    }
  }
}

Used commandline:

$ datamodel-codegen --input test.json --output model.py

Generated code from the schema:

from __future__ import annotations

from typing import Dict

from pydantic import BaseModel, Extra, Field


class Result(BaseModel):
    pass

    class Config:
        extra = Extra.allow


class Model(BaseModel):
    test_id: str = Field(..., description='test ID')
    test_ip: str = Field(..., description='test IP')
    result: Dict[str, Result]

When instantiating this class with the following code:

model = Model(test_id="test", test_ip="test", result={"a": 5})

The following error is raised from pydantic:

pydantic.error_wrappers.ValidationError: 1 validation error for Model
result -> a
  value is not a valid dict (type=type_error.dict)

Expected behavior

The issue can be solved by adding __root__ atrribute to Result model:

class Result(BaseModel):
    __root__: int

    class Config:
        extra = Extra.allow

Version:

  • OS: Ubuntu 16.04
  • Python version: 3.7
  • datamodel-code-generator version: 0.6.23

Additional context
I have found the similar issue but solution works only for arrays:

"result": {
      "type": "object",
      "additionalProperties": {
        "type": "array",
        "items": {
          "type": "integer"
        }
      }
    }
bug

Most helpful comment

@koxudaxi
Thank you a lot for your quick response! The new version works as expected)

All 3 comments

@MikeZaharov
Thank you for creating this issue.
I confirmed this problem. I will fix it.

@MikeZaharov
I have released a fixed version as 0.6.24 馃殌

@koxudaxi
Thank you a lot for your quick response! The new version works as expected)

Was this page helpful?
0 / 5 - 0 ratings