syntactic
syntactic

Reputation: 196

Have pydantic object dict() method return custom representation for non-pydantic type

I have a pydantic object that has some attributes that are custom types. I was able to create validators so pydantic can validate this type however I want to get a string representation of the object whenever I call the pydantic dict() method. Heres an example:

class MongoId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if isinstance(v, str):
            return ObjectId(v)
        if not isinstance(v, ObjectId):
            raise ValueError("Invalid ObjectId")
        return v
    

class User(BaseModel):
    uid: MongoId

user = User(...)

When I call user.dict() I want to get a string representation of the uid attribute not an object representation for that attribute.

I tried having the custom type inherit the BaseModel class and then implementing a dict() method inside hoping it would overload it but it doesn't seem to get called

Upvotes: 0

Views: 2157

Answers (1)

Denis Artyushin
Denis Artyushin

Reputation: 374

There is a similar issue being discussed here: https://github.com/pydantic/pydantic/issues/1409

One solution:

  1. Create JSON serialization for your type
class User(BaseModel):

    class Config:
        json_encoders = {
            # custom output conversion for your type
            MongoId: lambda mid: str(mid)
        }
  1. Run the following command
user = User(...)
user_as_dict = json.loads(user.json())

Upvotes: 1

Related Questions