Recently I was involved in developing a PPE response network built by The Luminosity Lab at Arizona State University. Its backend was built using Flask. This was my first time working on a Flask application and I was surprised that it is not trivial to elegantly serialize the database model classes to JSON. There are multiple approaches that can be used to serialize the classes. In this post, I will introduce you to the approach that I liked the most.
The SQLAlchemy-serializer library makes serializing objects to JSON quite easy and it has got quite a few customizations that let you handle all of your custom use cases.
Mixin for SQLAlchemy models serialization without pain. If you want to serialize SQLAlchemy model instances with only…
Install the library
Install the library using
pip install SQLAlchemy-serializer
Define the Model Class
Define your database’s model class using
Define a Custom Serializer
If your database table uses classes like
Geometry etc., you will need to define a custom serializer for it.
serialize_types = (
(UUID, lambda x: str(x)),
Check out the documentation to see what data types are natively supported by the library.
Define fields to serialize
You can specify the list of fields you want to serialize by using the
serialize_only field in your model class.
serialize_only = ('id', 'email_id', 'role_type', 'users.id')
Note: In this example, we have a
users relationship defined and we want to serialize just the
id field of
Define fields to exclude
You can exclude the whole relationship object by using a minus(
-) symbol before the relationship name.
serialize_rules = ('-merchants')
In this example, we want to exclude all the fields of the
merchants field when serializing the JSON.
Avoid circular dependency
If you have a relationship and foreign key defined in your models, you could run into a circular dependency issue. Suppose you have the following model classes defined:
Notice that the login class has
users added in its
serialize_only field. With this setup you will face a maximum recursion depth exceeded exception. The serializer will find an instance of the same class among the model’s relationships. To avoid this you need to define where the serialization should stop:
serialize_rules = ('-users.login.users',)
With the serializer mixin in place, its very simple to serialize your object to JSON.