I am trying to parse MongoDB data to a pydantic schema but fail to read its _id
field which seem to just disappear from the schema.
The issue is definitely related to the underscore in front of the object attribute. I can’t change _id
field name since that would imply not parsing the field at all.
Please find below the code I use (using int
instead of ObjectId
for the sake of simplification)
JavaScript
x
18
18
1
from pydantic import BaseModel
2
3
class User_1(BaseModel):
4
_id: int
5
6
data_1 = {"_id": 1}
7
8
parsed_1 = User_1(**data_1)
9
print(parsed_1.schema())
10
11
class User_2(BaseModel):
12
id: int
13
14
data_2 = {"id": 1}
15
16
parsed_2 = User_2(**data_2)
17
print(parsed_2.schema())
18
User_1
is parsed successfully since its _id
field is required but can’t be read afterwards.
User_2
works in the above example by fails if attached to Mongo which doesn’t provide any id
field but _id
.
Output of the code above reads as follows:
JavaScript
1
3
1
User_1 {'title': 'User_1', 'type': 'object', 'properties': {}}
2
User_2 {'title': 'User_2', 'type': 'object', 'properties': {'id': {'title': 'Id', 'type': 'integer'}}, 'required': ['id']}
3
Advertisement
Answer
you need to use an alias for that field name
JavaScript
1
5
1
from pydantic import BaseModel, Field
2
3
class User_1(BaseModel):
4
id: int = Field( , alias='_id')
5
See the docs here.