How to convert the result of an orm object to an SQLAlchemy object in JSON format?
I am currently using sqlalchemy reflection to mirror tables from a database. Think of it, I have a User table and a table of addresses that I reflect in the database. A user object is one to one related to an address object. Below is the code reflecting the table from the database and using the mapper class to match the relationship.
from sqlalchemy import Table from sqlalchemy.orm import mapper, relationship user_reflection = Table('user', metadata, autoload=True, autoload_with=engine) class User(object): def __init__(self, id, name, dob): self.id = id self.name = name self.dob = dob address_reflection = Table('address', metadata, autoload=True, autoload_with=engine) mapper(User, user_reflection, properties={ 'address': relationship(SourceAddress, uselist=False) } )
Now when I query an object using sqlalchemy orm
user = session.query(User).first() user_dict = object_to_dict(user)
Now that I want to convert the user object to a dict I use the method below.
def object_to_dict(obj): columns = [column.key for column in class_mapper(obj.__class__).columns] get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (c, getattr(obj, c)) return dict(map(get_key_value, columns))
However, the object_to_dict methods work fine and return a valid dic if the returned object is a user that is not related to another table. If the user object is related, the object_to_dict method does not automatically expand the relationship object and convert it to a dict.
Can someone suggest me how I can automatically determine if the returned user object has relationships and extends the relationship object to dict if it has one, etc. for any number of children.