Skip to content

Instantly share code, notes, and snippets.

@JRudransh
Last active August 24, 2024 07:39
Show Gist options
  • Save JRudransh/eb9d674a630142c09bd19b633293c46e to your computer and use it in GitHub Desktop.
Save JRudransh/eb9d674a630142c09bd19b633293c46e to your computer and use it in GitHub Desktop.
Python Serializer for MongoDB which can serialize all ObjectId
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