Created
May 8, 2018 11:01
-
-
Save vcancy/d3ffb196f4d348c03882fab0258f05c3 to your computer and use it in GitHub Desktop.
sqlalchemy object to dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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