Skip to content

Instantly share code, notes, and snippets.

@vcancy
Created May 8, 2018 11:01
Show Gist options
  • Save vcancy/d3ffb196f4d348c03882fab0258f05c3 to your computer and use it in GitHub Desktop.
Save vcancy/d3ffb196f4d348c03882fab0258f05c3 to your computer and use it in GitHub Desktop.
sqlalchemy object to dict
from sqlalchemy import inspect
def alchemy_to_dict(obj):
# an SQLAlchemy class
fields = {}
for field in [c.key for c in inspect(obj).mapper.column_attrs]:
data = obj.__getattribute__(field)
try:
if isinstance(data, datetime):
data = data.strftime('%Y-%m-%d %H:%M:%S')
json.dumps(data) # this will fail on non-encodable values, like other classes
fields[field] = data
except TypeError:
fields[field] = None
# a json-encodable dict
return fields
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment