import sys; print(sys.version): 3.6.5import pydantic; print(pydantic.VERSION): 0.13json_encoders do not seem to work for recursive models:
from pydantic import BaseModel
class AttachedTemplate(BaseModel):
id: str
name: str
class DeviceTemplate(BaseModel):
id: str
name: str
general_template: AttachedTemplate
class Config:
json_encoders = {
AttachedTemplate: lambda v: "custom",
}
t = DeviceTemplate(
id="id1",
name="template1",
general_template={"id": "attached_id1", "name": "attached1"}
)
t.json()
# > '{"id": "id1", "name": "template1", "general_template": {"id": "attached_id1", "name": "attached1"}}'
That's because sub-models are already converted to dicts when the data is passed to json.dumps.
See
and
I'm not sure that this warents a change in pydantic, but you could achieve the same thing by opperating directly on model.__values__, eg. have your own method
class CustomModel(BaseModel):
def json(self):
return json.dumps(self.__values__, default=my_encoder_function)
Closing for now, but feel free to ask further questions here if you wish.
@samuelcolvin
Thanks for the explanation and hint about __values__. I tried this way as well as overriding dict on submodel and it works as expected.
Can we add this caveat about json_encoders to the docs? https://pydantic-docs.helpmanual.io/#json-serialisation
Most helpful comment
@samuelcolvin
Thanks for the explanation and hint about
__values__. I tried this way as well as overridingdicton submodel and it works as expected.Can we add this caveat about
json_encodersto the docs? https://pydantic-docs.helpmanual.io/#json-serialisation