Pydantic: json_encoders do not work for recursive models

Created on 29 Aug 2018  路  2Comments  路  Source: samuelcolvin/pydantic


  • OS: macOS
  • Python version import sys; print(sys.version): 3.6.5
  • Pydantic version import pydantic; print(pydantic.VERSION): 0.13

json_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"}}'

Most helpful comment

@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

All 2 comments

That's because sub-models are already converted to dicts when the data is passed to json.dumps.

See

https://github.com/samuelcolvin/pydantic/blob/08396467887e911bf890cb936209a730fc582fce/pydantic/main.py#L220-L223

and

https://github.com/samuelcolvin/pydantic/blob/08396467887e911bf890cb936209a730fc582fce/pydantic/main.py#L333

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Gaunt picture Gaunt  路  19Comments

samuelcolvin picture samuelcolvin  路  30Comments

kryft picture kryft  路  35Comments

chopraaa picture chopraaa  路  18Comments

cazgp picture cazgp  路  34Comments