Created
July 13, 2021 07:29
-
-
Save cadd/10e800b3f94931490736142068e2893e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pydantic import BaseModel, Field | |
| from pymongo import MongoClient | |
| from bson import ObjectId | |
| from typing import Optional | |
| client = MongoClient() | |
| db = client.test | |
| class PyObjectId(ObjectId): | |
| @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 __modify_schema__(cls, field_schema): | |
| field_schema.update(type='string') | |
| class User(BaseModel): | |
| id: Optional[PyObjectId] = Field(alias='_id') | |
| name: str | |
| username: str | |
| email: str | |
| class Config: | |
| arbitrary_types_allowed = True | |
| json_encoders = { | |
| ObjectId: str | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment