How to serialize custom type that extends builtin type in pydantic?

Viewed 475

currently I'm working with FastAPI and pydantic as serializer. Problem is, we're using snowflake id on the server side, which means we need to convert those ids to string before sending to client (javascript) because the id is larger than JS's MAX SAFE INTEGER.

So I tried to create a new class which extends python's int type and customize how it will be serialized and deserialized. Here's my code:

class SnowflakeId(int):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v: str):
        return int(v)

    @classmethod
    def __modify_schema__(cls, field_schema: dict) -> None:
        field_schema['type'] = 'string'

And here is the model:

class BaseModel(pydantic.BaseModel):
    __abstract__ = True

    id: SnowflakeId

    class Config:
        orm_mode = True
        arbitrary_types_allowed = True
        json_encoders = {
            SnowflakeId: lambda v: str(v)
        }
        alias_generator = camelize
        allow_population_by_field_name = True

It works fine when deserializing from json string into int id, however, when it comes to the serialization, the output still is integer. I want it to serialize the id into string also, is it possible?

0 Answers
Related