datamodel-code-generator
datamodel-code-generator copied to clipboard
Creation from an "empty" object schema results with a Model containing an empty dict or None
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 I'm sorry for my late reply. I just understood the problem. I will fix it.
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.
@koxudaxi If you'd give me some advice where to look to fix the code - I might do it.
@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 🤔
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.