![](/img/trans.png)
[英]How to parse a pydantic model with a field of type "Type" from json?
[英]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
在上面的例子中工作失败,如果附加到不提供任何id
字段但_id
Mongo。
上面代码的输出如下:
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')
请参阅此处的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.