Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ULID can't be serialized with Pydantic's dump model to json #20

Closed
Avihais12344 opened this issue Mar 29, 2024 · 4 comments
Closed

ULID can't be serialized with Pydantic's dump model to json #20

Avihais12344 opened this issue Mar 29, 2024 · 4 comments

Comments

@Avihais12344
Copy link
Contributor

Hello,
I see this package has support for Pydantic. I want to use the model_dump_json so I could serialize my model to json in my webserver. But I can't serialize ULID. It seems like an implementation error.

How to reproduce:

  • Pip freeze:

    annotated-types==0.6.0
    pydantic==2.6.4
    pydantic_core==2.16.3
    python-ulid==2.3.0
    typing_extensions==4.10.0
  • Code:

    from pydantic import BaseModel
    from pydantic_core import PydanticSerializationError
    from ulid import ULID
    
    
    class MyModel(BaseModel):
        my_id: ULID
    
    my_test = MyModel(my_id=ULID())
    
    try:
        print(f"{my_test.model_dump_json()=}")
    except PydanticSerializationError as e:
        print(f"{e=}")
    
    print(f"{my_test.model_dump()=}")

    The output would be:

    e=PydanticSerializationError(Error serializing to JSON: PydanticSerializationError: Unable to serialize unknown type: <class 'ulid.ULID'>)
    my_test.model_dump()={'my_id': ULID(01HT4RBZKNQ9DFXZQ8DW02Z27Y)}

    We can see ha model dump is supported, but not model dump json.

@Avihais12344
Copy link
Contributor Author

A bypass to this problem is to build your own field_serializer:

class MyModel(BaseModel):
    my_id: ULID
    
    @field_serializer("my_id", return_type="str", when_used="unless-none")
    @staticmethod
    def serialize_ulid(ulid: ULID) -> str:
        return str(ulid)

Then, the code above would work. But I would want support from this library so I wouldn't need to copy-paste it.

@Avihais12344
Copy link
Contributor Author

Opened a PR to solve this issue: #21

@orfisko
Copy link

orfisko commented Apr 2, 2024

Sorry but this is a major defect. You will get a ton of extra users by having Pydantic support, so serialization should be supported. I just lost an hour because I suspected I did something wrong in my dependencies. Than finding out that this basic feature is not supported is disappointing.

@mdomke
Copy link
Owner

mdomke commented Apr 2, 2024

This should be fixed in version 2.4.0 based on the pull-request from @Avihais12344

@mdomke mdomke closed this as completed Apr 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants