Skip to content

Instantly share code, notes, and snippets.

@dongyx dongyx/sqla2dict.py
Last active Apr 12, 2019

Embed
What would you like to do?
Convert the SQLAlchemy model to the JSON-encodable dictionary
# Explained at http://yxdong.me/posts/dumping-sqlalchemy-models-to-json.html
import json
from sqlalchemy.orm.properties 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:
continue
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
json.dumps(val)
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]
else:
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.