Das Ziel wäre die (De-)Serialisierung, ohne eine Verschachtelungsebene hinzuzufügen.
Verschachtelungsbeispiel:
Code: Select all
from pydantic import BaseModel, validator
class Foo(BaseModel):
foo: str
@validator('foo')
def must_be_xxx(cls, v):
if v != 'xxx':
raise ValueError('must be xxx')
class Bar(BaseModel):
bar: Foo
x = Bar(bar=Foo(foo='xxx'))
print(x.json()) # {"bar": {"foo": "xxx"}}
Code: Select all
from pydantic import BaseModel, validator
class FooScalar(BaseModel, str):
# 1) running this code produces the following exception :
# TypeError: multiple bases have instance lay-out conflict
# 2) What class or __dunder__ methods to add ?
# What/how to use @validator and with what ?
pass
class Bar(BaseModel):
bar: FooScalar
# desired behaviour and output
y = Bar(bar=FooScalar('xxx'))
print(y.json()) # {"bar": "xxx"}