[Python] pydantic get field alias based on field value with python object

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have pydantic model as below.

    from typing import Annotated
    from bson import ObjectId

    from pydantic import Field
    from pydantic import EmailStr
    from pydantic import BaseModel
    from pydantic import BeforeValidator
    from pydantic import ConfigDict
    from pydantic import AwareDatetime
    from pydantic import field_validator

    # Represents an ObjectId field in the database.
    # It will be represented as a `str` on the model so that it can
    # be serialized to JSON.
    PyObjectId = Annotated[str, BeforeValidator(str)]

    class DBTableBase(BaseModel):
    # The primary key for the Table, stored as a `str` on the instance.
    # This will be aliased to `_id` when sent to MongoDB,
    # but provided as `id` in the API requests and responses.
    id: PyObjectId | None = Field(alias="_id",
    serialization_alias="id",
    default=None)
    model_config = ConfigDict(
    json_encoders={ObjectId: str},
    json_schema_extra={
    "example": {
    "id": "BSON_ID"
    }
    },
    )

    class ClientModel(DBTableBase):
    first_name: str
    last_name: str


    I create object and print the model_dump

    In [16]: a = ClientModel(_id=ObjectId(), first_name="first_name", last_name="last_name")

    In [17]: a
    Out[17]: ClientModel(id='67ce7b6190a330f1f5018315', first_name='first_name', last_name='last_name')

    In [18]: a.model_dump()
    Out[18]:
    {'id': '67ce7b6190a330f1f5018315',
    'first_name': 'first_name',
    'last_name': 'last_name'}


    This will convert _id of ObjectId to str as id in model_dump.

    Is there any way to get it reverse like I pass id as str and will return _id as ObjectId?

    In [19]: b = ClientModel(id='67ce7b6190a330f1f5018315', first_name='first_name', last_name='last_name')

    In [20]: b.model_dump()
    Out[20]: {'id': None, 'first_name': 'first_name', 'last_name': 'last_name'}

    Continue reading...

Compartilhe esta Página