0

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'}
4
  • Why not switching the validation_alias and the serialization_alias then? Note that you can also do .model_dump(by_alias=False) if needed. Commented Mar 12 at 10:15
  • let me try this Commented Mar 12 at 16:00
  • @lord_haffi this is not working, I dont want to validate, I want the ObjectId object in the model. Commented Mar 18 at 4:34
  • 1
    Ahh, you want to have ObjectId as a custom type inside your model? Then take a look here: docs.pydantic.dev/latest/concepts/types/… Commented Mar 18 at 9:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.