Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
Convert a JSON-encodable dictionary to an SQLAlchemy model
# Explained at http://yxdong.me/posts/loading-sqlalchemy-models-from-json.html
''' Usage
model = dict2sqla(the_dict_from_json, cls=the_model_class, session=sqlalchemy_session)
'''
from sqlalchemy.orm.properties import ColumnProperty
from sqlalchemy.orm.relationships import RelationshipProperty
def _get_remote(remote, remotecls, session):
if isinstance(remote, dict):
return dict2sqla(remote, remotecls, session)
else:
return session.query(remotecls).get(remote)
def dict2sqla(dct, cls, session, ignores=None):
ret = cls()
ignores = ignores or hasattr(cls, "__ignores__") and cls.__ignores__ or []
for prop in cls.__mapper__.iterate_properties:
key = prop.key
if key in ignores or key not in dct:
continue
val = dct[key]
if isinstance(prop, ColumnProperty):
setattr(ret, key, val)
elif isinstance(prop, RelationshipProperty):
remotecls = getattr(cls, key).property.mapper.class_
if isinstance(val, list):
setattr(ret, key, [_get_remote(v, remotecls, session) for v in val])
else:
setattr(ret, key, _get_remote(val, remotecls, session))
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.