2021-07-27

Pydantic nested models aliases

My service is built with FastAPI and Pydantic. By the agreement, we use snail_case for application variables, and camelCase for JSON returned to a client-side from endpoints. The issue is that nested models serialize, ignoring the aliases.

Due to the architectural particularities, I have to create models from TypedDicts.

class SubModel(TypedDict):
    red_status: int    
    green_status: int   


class MainModel(TypedDict):
    time_unit: str
    events: List[SubModel]


class ModelConfig:
    alias_generator = humps.camelize
    allow_population_by_field_name = True


MySubModel = create_model_from_typeddict(
    SubModel, 
    __config__=ModelConfig
)

MyMainModel = create_model_from_typeddict(
    MainModel, 
    __config__=ModelConfig
)

events = list(map(lambda x: SubModel(**x), data))

data = MyMainModel(
    time_unit="day", 
    events=events 

)

Here is what I have as a result:

>>> events[0].json(by_alias=True)
{"redStatus": 15, "greenStatus": 12}
>>> data.json(by_alias=True)
{"timeUnit": "day", "events": [{"red_status": 15, "green_status": 12}]

How to apply aliases on the nested model instances?



from Recent Questions - Stack Overflow https://ift.tt/3kTrXL4
https://ift.tt/eA8V8J

No comments:

Post a Comment