Skip to content

Instantly share code, notes, and snippets.

@dongyx dongyx/
Last active Apr 12, 2019

What would you like to do?
Convert a JSON-encodable dictionary to an SQLAlchemy model
# Explained at
''' Usage
model = dict2sqla(the_dict_from_json, cls=the_model_class, session=sqlalchemy_session)
from import ColumnProperty
from sqlalchemy.orm.relationships import RelationshipProperty
def _get_remote(remote, remotecls, session):
if isinstance(remote, dict):
return dict2sqla(remote, remotecls, session)
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:
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])
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.