本周,我开始使用 MongoDB 和 Flask,因此我找到了一篇有用的文章,介绍如何通过使用 PyDantic 库定义 MongoDB 的模型来将它们一起使用。然而,这篇文章有点过时了,大部分可以更新到新的 PyDantic 版本,但问题是 ObjectId 是第三方字段,并且在版本之间发生了很大的变化。
本文使用以下代码定义了ObjectId:
from bson import ObjectId
from pydantic.json import ENCODERS_BY_TYPE
class PydanticObjectId(ObjectId):
"""
Object Id field. Compatible with Pydantic.
"""
@classmethod
def __get_validators__(cls):
yield cls.validate
#The validator is doing nothing
@classmethod
def validate(cls, v):
return PydanticObjectId(v)
#Here you modify the schema to tell it that it will work as an string
@classmethod
def __modify_schema__(cls, field_schema: dict):
field_schema.update(
type="string",
examples=["5eb7cf5a86d9755df3a6c593", "5eb7cfb05e32e07750a1756a"],
)
#Here you encode the ObjectId as …
Run Code Online (Sandbox Code Playgroud)