Custom JSON encoder not working with nested model

Viewed 190

I am trying to create a custom JSON encoding for a nested Pydantic model. I have simplified the problem to the following example:

from pydantic import BaseModel


class SubModel(BaseModel):
    name: str
    short_name: str


class TestModel(BaseModel):
    sub_model: SubModel

    class Config:
        json_encoders = {SubModel: lambda s: s.short_name}


model = TestModel(sub_model=SubModel(name="Sub Model", short_name="SM"))

print(model)
print(model.json())

I am expecting the final line to output:

{"sub_model": "SM"}

But instead I am getting the output as if I never even defined my own json_encoders:

{"sub_model": {"name": "Sub Model", "short_name": "SM"}}

How can I correctly define a JSON encoder for another Pydantic model?

2 Answers
Related