24 lines
635 B
Python
24 lines
635 B
Python
from bson import ObjectId
|
|
from pydantic import GetJsonSchemaHandler
|
|
from pydantic.json_schema import JsonSchemaValue
|
|
|
|
|
|
class PyObjectId(ObjectId):
|
|
"""Custom ObjectId type for Pydantic v2 to handle MongoDB _id"""
|
|
|
|
@classmethod
|
|
def __get_validators__(cls):
|
|
yield cls.validate
|
|
|
|
@classmethod
|
|
def validate(cls, v):
|
|
if not ObjectId.is_valid(v):
|
|
raise ValueError("Invalid ObjectId")
|
|
return ObjectId(v)
|
|
|
|
@classmethod
|
|
def __get_pydantic_json_schema__(
|
|
cls, schema: JsonSchemaValue, handler: GetJsonSchemaHandler
|
|
) -> JsonSchemaValue:
|
|
return {"type": "string"}
|