The purpose of this article was to show how to show how to transparently serialize dictionaries as JSON fields in your database through SQLAlchemy and access them from your code as dictionaries.
Quite often the case is that some request is supposed to return a set of these objects to user. The use case might be e.g. a REST interface and user is querying, let’s say, blog posts. Some of the post objects however might include fields which are not meant for or are just not necessary for the user. Primary keys for example. This is why I have adopted way of creating an super class Serializable with a method to turn all the selected keys and their values in a model into a dictionary.
To use this in models, the model must inherit from Serializable. In case of JSON fields the thing is a bit problematic. In this specific case the JSON field is only to used by clients, so no efficient queries are required for the information in the field. However dictionaries and JSON not being common data types in SQL databases the model must include a special handling to serialize and deserialize the dictionary into JSON string presentation and back. This is a quite useful case for Python descriptors. Especially in SQLAlchemy there is a special kind of descriptor like entities known as hybrid properties
After this it’s quite convenient to use your model
Link to full source code