![](/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.