如何从 pydantic 模型解析和读取“_id”字段?

How to parse and read "_id" field from and to a pydantic model?

我正在尝试将 MongoDB 数据解析为 pydantic 模式,但无法读取它的 _id 字段,该字段似乎刚刚从模式中消失。
这个问题肯定与对象属性前面的下划线有关。我无法更改 _id 字段名称,因为这意味着根本不解析该字段。
请在下面找到我使用的代码(为简化起见,使用 int 而不是 ObjectId

from pydantic import BaseModel

class User_1(BaseModel):
    _id: int

data_1 = {"_id": 1}

parsed_1 = User_1(**data_1)
print(parsed_1.schema())

class User_2(BaseModel):
    id: int

data_2 = {"id": 1}

parsed_2 = User_2(**data_2)
print(parsed_2.schema())

User_1 解析成功,因为它的 _id 字段是必需的,但之后无法读取。 User_2 在上面的例子中工作失败,如果附加到 Mongo 不提供任何 id 字段但 _id.

上面代码的输出如下:

User_1  {'title': 'User_1', 'type': 'object', 'properties': {}}
User_2  {'title': 'User_2', 'type': 'object', 'properties': {'id': {'title': 'Id', 'type': 'integer'}}, 'required': ['id']}

您需要为该字段名称使用别名

from pydantic import BaseModel, Field

class User_1(BaseModel):
    id: int = Field(..., alias='_id')

查看文档 here