I have the following structure of the models using Pydantic library. I created some of the classes, and one of them contains list of items of another, so the problem is that I can't parse json using this classes:
class FileTypeEnum(str, Enum):
file = 'FILE'
folder = 'FOLDER'
class ImportInModel(BaseModel):
id: constr(min_length=1)
url: constr(max_length=255) = None
parentId: str | None = None
size: PositiveInt | None = None
type: FileTypeEnum
@root_validator
def check_url(cls, values: dict):
file_type = values['type']
file_url = values['url']
if file_type == FileTypeEnum.folder and file_url is not None:
raise ValueError(
f'{file_type}\'s type file has {file_url} file url!'
)
@root_validator
def check_size(cls, values: dict):
file_type = values['type']
file_size = values['size']
if file_type == FileTypeEnum.file and file_size is None:
raise ValueError(
f'{file_type}\'s type file has {file_size} file size!'
)
class ImportsInModel(BaseModel):
items: list[ImportInModel]
updateDate: datetime
class Config:
json_encoders = {
datetime: isoformat
}
json_loads = ujson.loads
@validator('items')
def check_parent(cls, v):
for item_1 in v:
for item_2 in v:
print(item_1.type, item_1.parentId, item_2.id, item_2.type)
assert item_1.type == FileTypeEnum.file \
and item_1.parentId == item_2.id \
and item_2.type == FileTypeEnum.folder
But then I use it like
try:
json_raw = '''{
"items": [
{
"id": "элемент_1_4",
"url": "/file/url1",
"parentId": "элемент_1_1",
"size": 234,
"type": "FILE"
}
],
"updateDate": "2022-05-28T21:12:01.000Z"
}
'''
ImportsInModel.parse_raw(json_raw)
# print(json_)
except ValidationError as e:
print(e)
It gives me error:
1 validation error for ImportsInModel items -> 0 ->
__root__
'NoneType' object is not subscriptable (type=type_error)
And I have no idea what's wrong, because it literally copy of the documentation.