'pydantic (different) Field name and/or alias in Model Config json_encoders

to talk to an foreign API I don't want/need the Submodel but only it's id. This is working well with using json_encoders in the Model Config.

Because I only return the id I want a different alias (and maybe also name) for it. Any thoughts how I can accomplish that?

from pydantic import BaseModel, Field

class City(BaseModel):
    id: int
    name: str

class User(BaseModel):
    name: str
    city: City = Field(alias="town")

    class Config:
        allow_population_by_field_name = True
        json_encoders = {
            # not working: City: lambda a = Field(alias="city_id") : a.id
            City: lambda a : a.id
        }

john = User(name='john', city=City(id=1, name='Geneva'))

# This is fine
print(john.json()) # {"name": "john", "city": {"id": 1, "name": "Geneva"}}
# Also this is fine
print(john.json(by_alias=True)) # {"name": "john", "town": {"id": 1, "name": "Geneva"}}

# here I like to have 'city_id' and not 'city'
print(john.json(models_as_dict=False)) # {"name": "john", "city": 1}
# here I like to have 'town_id' and not 'town'
print(john.json(models_as_dict=False, by_alias=True)) # {"name": "john", "town": 1}

Any hints are appreciated :-)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source