datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

Creation from an "empty" object schema results with a Model containing an empty dict or None

Open zalun opened this issue 3 years ago • 5 comments
trafficstars

Describe the bug I need an option to provide users with their own configuration with key names created by them. The model generated contains no __root__ therefore it does not hold any data

To Reproduce

Example schema:


openapi: 3.0.0

components:
  schemas:
    Configuration:
      type: object

    Item:
      type: object
      properties:
        configuration:
            $ref: '#/components/schemas/Configuration'

Used commandline:

$ datamodel-codegen \
    --input schema.yaml \
    --output schema.py \
    --field-constraints \
    --target-python-version 3.9 \
    --use-schema-description \
    --wrap-string-literal

Creates:

# ...
class Configuration(BaseModel):
    pass


class Item(BaseModel):
    configuration: Optional[Configuration] = None

Which fails the test:

from schema import Configuration, Item

def test_schema():
    data = {"configuration": {"some key": "some value"}}
    assert Item(**data).dict() == data

Expected behavior A model containing the __root__:

class Configuration(BaseModel):
    __root__: Optional[dict] = None
FAILED test_schema.py::test_schema - AssertionError: assert {'configuration': {}} == {'configuration': {'some key': 'some value'}}

Version:

  • OS: macOS
  • Python version: 3.9.7
  • datamodel-code-generator version: 0.11.15

zalun avatar Dec 17 '21 13:12 zalun

@zalun I'm sorry for my late reply. I just understood the problem. I will fix it.

koxudaxi avatar Jan 11 '22 17:01 koxudaxi

Thank you.

No worries, I made a workaround in my code.

Also thank you for the tool - I am sure I will also use it in the future.

zalun avatar Jan 12 '22 07:01 zalun

@koxudaxi If you'd give me some advice where to look to fix the code - I might do it.

zalun avatar May 18 '22 08:05 zalun

@zalun OK, I just came back. First, we should confirm the expected object. you expect the below about the model.

class Configuration(BaseModel):
    __root__: Optional[dict] = None

But, I recommend these models

class Item(BaseModel):
    configuration: Optional[dict] = None

Or,

Configuration = Dict

class Item(BaseModel):
   configuration: Optional[Configuration] = None

It means your opinion may not be kind for the user 🤔

koxudaxi avatar May 19 '22 15:05 koxudaxi

I think you're right - I've been thinking about using _root_ as it was similar to the way other objects have been implemented.

This would work better.

zalun avatar Jun 15 '22 17:06 zalun