Happy-Kunal / pydantic2avro

Generate Apache Avro schemas for Pydantic data models.
https://pypi.org/project/pydantic2avro/
MIT License
0 stars 0 forks source link

parse ObjectId #5

Open SROMCY opened 2 months ago

SROMCY commented 2 months ago

I need to use ObjectIds in my Pydantic Model as described in this issue: https://stackoverflow.com/questions/59503461/how-to-parse-objectid-in-a-pydantic-model

Is it possible to add this to pydantic2avro? image

zifo-10 commented 1 month ago

You can use the pyobjectID package to deal with ObjectID. package can be used in Pydantic models , Here are examples of how to implement it:

from pydantic import BaseModel
from pyobjectID import PyObjectId, MongoObjectId

class User(BaseModel):
    id: PyObjectId  # Automatically validates and converts to ObjectId
    name: str
    email: str

class GetFromMongo(BaseModel):
    id: MongoObjectId  # Automatically validates and converts to string

You can perform basic operations such as generating, validating, and converting ObjectIds:

from pyobjectID import (generate, PyObjectId, 
                        MongoObjectId, is_valid)

# Generate a new ObjectId
new_id = generate()
print(f"Generated ObjectId: {new_id}")

# Validate an ObjectId
valid = is_valid(new_id)
print(f"Is the ObjectId valid? {valid}")

# Convert a string to a PyObjectId
py_object_id = PyObjectId.to_object(new_id)
print(f"PyObjectId: {py_object_id}")

# Convert a PyObjectId to a string
mongo_object_id = MongoObjectId.to_string(py_object_id)
print(f"MongoObjectId: {mongo_object_id}")