Skip to content
Advertisement

Writing a pydantic object into a sqlalchemy json column

I’m looking for a way to have a pydantic object stored in a sqlalchemy json column. My attempts so far are being tripped up by a datetime field in the pydantic object. I feel like I’m missing something obvious.

My first attempt was to simply serialise the result of .dict(). But this doesn’t convert datetime objects to strings so the serialiser falls over. If I convert with .json then the result is a string and what’s stored in the database is the json of a string not a dict.

JavaScript
JavaScript

Advertisement

Answer

As Eduard Sukharev describes in his answer, you can set sqlalchemy to use a different json encoder.

It’s really well buried, but pydantic does give you access to it’s own json encoders which handle things like datetime automatically

JavaScript

… Then create a sqlalchemy engine with:

JavaScript

With that sqlalchemy will be able to handle .dict() results in pretty much the same way pydantic .json() works.

Note this doesn’t work for classes with their own custom encoders.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement