To convert a SQLAlchemy ORM row object to a Python dictionary, you can use the built-in functionality provided by SQLAlchemy or manually extract each attribute. Below are some methods to achieve this conversion:
Using SQLAlchemy's __table__.columns
Assuming you have a model class, you can use its __table__.columns attribute to iterate over column names and construct the dictionary:
from sqlalchemy.orm import Session
def object_as_dict(obj):
return {column.name: getattr(obj, column.name) for column in obj.__table__.columns}
# Example usage
# Assuming `Child` is a SQLAlchemy model
def get_child_as_dict(session: Session, child_id):
child = session.query(Child).get(child_id)
return object_as_dict(child) if child else None
Using the __dict__ Attribute
You can also leverage the __dict__ attribute of the SQLAlchemy model instance, although this might include additional internal state data, such as private fields prefixed with underscores:
def object_as_dict(obj):
return {key: value for key, value in vars(obj).items() if not key.startswith('_')}
# Example usage
def get_child_as_dict(session: Session, child_id):
child = session.query(Child).get(child_id)
return object_as_dict(child) if child else None
Using SQLAlchemy's inspect Function
Another way involves using sqlalchemy.inspection.inspect, which provides more formal access to the model's mapping and can be useful for complex models with relationships:
from sqlalchemy.inspection import inspect
def object_as_dict(obj):
return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
# Example usage
def get_child_as_dict(session: Session, child_id):
child = session.query(Child).get(child_id)
return object_as_dict(child) if child else None
Handling Relationships
If you need to also include related objects, you can extend these functions to iterate over relationships:
from sqlalchemy.orm import class_mapper
def object_as_dict(obj, include_relationships=False):
# Include columns
result = {c.key: getattr(obj, c.key) for c in class_mapper(obj.__class__).columns}
if include_relationships:
# Include relationships
for name, relation in class_mapper(obj.__class__).relationships.items():
related_obj = getattr(obj, name)
if related_obj is not None:
if relation.uselist:
result[name] = [object_as_dict(o) for o in related_obj]
else:
result[name] = object_as_dict(related_obj)
return result
# Example usage with relationships
def get_child_as_dict(session: Session, child_id):
child = session.query(Child).get(child_id)
return object_as_dict(child, include_relationships=True) if child else None
Notes
- Column Names: Ensure that the attribute names in your models match the column names if you're using any custom naming conventions.
- Performance: Be mindful of performance when converting a large number of rows, especially if using recursive relationship handling.
These methods allow you to easily convert SQLAlchemy objects to Python dictionaries, which can then be manipulated or serialized as needed.