Search code examples
pythonserializationdeserializationpydanticsnakecasing

Pydantic model parse pascal case fields to snake case


I have a Pydantic class model that represents a foreign API that looks like this:

class Position(BaseModel):
    AccountID: str
    AveragePrice: str
    AssetType: str
    Last: str
    Bid: str
    Ask: str
    ConversionRate: str
    DayTradeRequirement: str
    InitialRequirement: str
    PositionID: str
    LongShort: str
    Quantity: int
    Symbol: str
    Timestamp: str
    TodaysProfitLoss: str
    TotalCost: str
    MarketValue: str
    MarkToMarketPrice: str
    UnrealizedProfitLoss: str
    UnrealizedProfitLossPercent: str
    UnrealizedProfitLossQty: str

This is the names of the API endpoint that I need to point to. I simply want to change the pascal case fields to a pythonic design.

What I want is to deserialize the foreign API and serialize it back using Pydantic's BaseModel class.

My problem is that if I use Pydantic's class Fields like this:

class Position(BaseModel):
    account_id: str = Field(alias='AccountID')
    average_price: str = Field(alias='AveragePrice')
    asset_type: str = Field(alias='AssetType')
    last: str = Field(alias='Last')
    bid: str = Field(alias='Bid')
    ask: str = Field(alias='Ask')
    conversion_rate: str = Field(alias='ConversionRate')
    day_trade_requirement: str = Field(alias='DayTradeRequirement')
    initial_requirement: str = Field(alias='InitialRequirement')
    position_id: str = Field(alias='PositionID')
    long_short: str = Field(alias='LongShort')
    quantity: int = Field(alias='Quantity')
    symbol: str = Field(alias='Symbol')
    timestamp: str = Field(alias='Timestamp')
    todays_profit_loss: str = Field(alias='TodaysProfitLoss')
    total_cost: str = Field(alias='TotalCost')
    market_value: str = Field(alias='MarketValue')
    mark_to_market_price: str = Field(alias='MarkToMarketPrice')
    unrealized_profit_loss: str = Field(alias='UnrealizedProfitLoss')
    unrealized_profit_loss_percent: str = Field(alias='UnrealizedProfitLossPercent')
    unrealized_profit_loss_qty: str = Field(alias='UnrealizedProfitLossQty')

I can only deserialize it and not the other way around.

Any way I can do it for both "directions"?


Solution

  • Yes, it's possible, use .dict(by_alias=True), see example:

    from pydantic import BaseModel, Field
    
    
    class Position(BaseModel):
        account_id: str = Field(alias='AccountID')
    
    
    pos2 = Position(AccountID='10')
    
    print(pos2.dict())
    print(pos2.dict(by_alias=True))
    

    Output:

    {'account_id': '10'} 
    {'AccountID': '10'}