Search code examples
pythonpydantic

How to make serialization_alias the default behavior in Pydantic BaseModel


How do i make pydantic serialization_alias as default during model_dump().

from pydantic import BaseModel, Field



class ProjectStage(BaseModel):

    name: dict[str, int] = Field(..., serialization_alias="Username")

    

    class Config:

        pass



a = ProjectStage(name={'foo': 1})

Usual way

output: {'Username': {'foo': 1}}

print(a.model_dump(by_alias=True))

Make by_alias as default in basemodel config

Expected output: {'Username': {'foo': 1}}

print(a.model_dump())

Solution

  • For everyone looking for a solution to this. You can make another class to inherit and override the model_dump() function

    from pydantic import BaseModel, Field
    
    class DefaultDump(BaseModel):
        def model_dump(self, **kwargs) -> dict[str, Any]:
            return super().model_dump(by_alias=True, **kwargs)
    
    class ProjectStage(DefaultDump):
        name: dict[str, int] = Field(..., serialization_alias="Username")
    
    a = ProjectStage(name={'foo': 1})
    
    # Output: {'Username': {'foo': 1}}
    print(a.model_dump())