ORM and objects with properties that need conversion to write to database

12 views
Skip to first unread message

Richard Damon

unread,
Oct 7, 2020, 10:38:35 PM10/7/20
to sqlal...@googlegroups.com
I am working on a app using SQLAlchemy's ORM layer to interface to the
database, but I am running into an issue that if an object has
'complicated' property, like a UUID, that SQLAlchemy doesn't know how to
handle. One option would be to make the propery actually only hold a
database suitable representation, and I see an option to add a
'reconstructor' to convert a value read from the database into an
object. Is there a similar way that when writing the object, to indicate
how to convert the object into a format that can be put into the database?

--
Richard Damon

Simon King

unread,
Oct 8, 2020, 4:55:23 AM10/8/20
to sqlal...@googlegroups.com
The usual pattern is to create a custom datatype using
sqlalchemy.types.TypeDecorator. You would override the
process_bind_baram and process_result_value methods to convert objects
between the python and database representations:

https://docs.sqlalchemy.org/en/13/core/custom_types.html#augmenting-existing-types

For the specific case of UUIDs, there is an example in the docs that
will use Postgres' UUID type against postgres, and CHAR against other
databases:

https://docs.sqlalchemy.org/en/13/core/custom_types.html#backend-agnostic-guid-type

Hope that helps,

Simon

Richard Damon

unread,
Oct 8, 2020, 7:06:16 AM10/8/20
to sqlal...@googlegroups.com
Thank you, that looks like what I was looking for but didn't know what
it was called.
--
Richard Damon

Reply all
Reply to author
Forward
0 new messages