Skip to content

Instantly share code, notes, and snippets.

@dongyx dongyx/
Last active Apr 12, 2019

What would you like to do?
Convert the SQLAlchemy model to the JSON-encodable dictionary
# Explained at
import json
from import ColumnProperty
from sqlalchemy.orm.relationships import RelationshipProperty
def _get_primary_key(model):
return getattr(model, model.__mapper__.primary_key[0].key)
def sqla2dict(model, foreign_keys=True, relationships=False, excludes=None):
excludes = excludes or hasattr(model, "__excludes__") and model.__excludes__ or []
ret = {}
for prop in model.__mapper__.iterate_properties:
key = prop.key
if key in excludes:
val = getattr(model, key)
if isinstance(prop, ColumnProperty) \
and (foreign_keys or not prop.columns[0].foreign_keys):
try: # This will fail on non-encodable types like DateTime
except TypeError:
val = str(val)
ret[key] = val
elif isinstance(prop, RelationshipProperty) and relationships:
if prop.uselist:
ret[key] = [_get_primary_key(v) for v in val]
ret[key] = _get_primary_key(val)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.