Last active
August 24, 2024 07:39
-
-
Save JRudransh/eb9d674a630142c09bd19b633293c46e to your computer and use it in GitHub Desktop.
Python Serializer for MongoDB which can serialize all ObjectId
This file contains 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 bson import ObjectId | |
from pydantic import BaseModel | |
class Base(BaseModel): | |
def __init__(self, **kwargs): | |
super().__init__(**self.serealize(kwargs)) | |
def serealize(self, data: dict) -> dict: | |
final = {} | |
for key, value in data.items(): | |
if isinstance(value, ObjectId): | |
final[key] = str(value) | |
elif isinstance(value, dict): | |
final[key] = self.serealize(value) | |
elif isinstance(value, list): | |
final[key] = [self.serealize(item) for item in value] | |
else: | |
final[key] = value | |
return final |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment