What is the new way to declare Mongo ObjectId with PyDantic v2.0^? – Pydantic

by
Ali Hasan
llama-cpp-python mongodb pydantic python-3.x

Quick Fix: Do not wrap ObjectId Annotation value in quotes.

The Problem:

Problem Statement:

How to implement the ObjectId field for MongoDB in the latest version of PyDantic library for Python?

The Solutions:

Solution 1:

The new way of defining custom data types in PyDantic v2.0 and above involves using the `Annotated` type annotation and implementing the `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__` methods on a custom annotation class. Third-party types can be handled by defining callables that validate and serialize the type.

Q&A

How do you define a custom type in Pydantic’s latest version?

Use Annotated with a custom annotation class that has a __get_pydantic_core_schema__ method to define custom types.

How to set a custom type as an ObjectId in Pydantic?

Use ObjectIdPydanticAnnotation as the annotation for the ObjectId field.

How to validate an ObjectId in Pydantic?

Use validate_object_id method in ObjectIdPydanticAnnotation to validate the ObjectId.

Video Explanation:

The following video, titled "FastAPI, Pydantic and MongoDB for Beginners - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Before pushing it to MongoDB collection, new record validation is done with Pydantic. I like the flexibility of MongoDB Motor async library ...