Skip to content
Advertisement

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

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

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

Advertisement

Answer

you need to use an alias for that field name

JavaScript

See the docs here.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement