У меня есть модель Pydantic, как показано ниже. < /p>
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
Я создаю объект и печатаю 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'}
Это будет преобразовать _id of objectId в str как id в model_dump .
есть ли способ сделать это, как I Pass id как str и вернуть _id
Подробнее здесь: https://stackoverflow.com/questions/794 ... hon-object
Pydantic Get Field Alias на основе значения поля с объектом Python ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Наследует help_text из django.db.models.Field в rest_framework.serializer.Field
Anonymous » » в форуме Python - 0 Ответы
- 70 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Наследует help_text из django.db.models.Field в rest_framework.serializer.Field
Anonymous » » в форуме Python - 0 Ответы
- 75 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Наследует help_text из django.db.models.Field в rest_framework.serializer.Field
Anonymous » » в форуме Python - 0 Ответы
- 65 Просмотры
-
Последнее сообщение Anonymous
-