Rumah >pembangunan bahagian belakang >Tutorial Python >sqlalchemy对象转dict的示例
if isinstance(obj.__class__, DeclarativeMeta):
# an SQLAlchemy class
#该类的相关类型,即直接与间接父类
cla = obj.__class__.__mro__
#过滤不需要的父类
cla = filter(lambda c: hasattr(c, '__table__'), filter(lambda c: isinstance(c, DeclarativeMeta), cla))
columns = []
map(lambda c: columns.extend(c.__table__.columns), cla[::-1])
# columns = obj.__table__.columns
if filtrate and isinstance(filtrate, (list, tuple)):
fields = dict(map(lambda c: (c.name, getattr(obj, c.name)), filter(lambda c: not c.name in filtrate, columns)))
else:
fields = dict(map(lambda c: (c.name, getattr(obj, c.name)), columns))
# fields = dict([(c.name, getattr(obj, c.name)) for c in obj.__table__.columns])
if rename and isinstance(rename, dict):
#先移除key和value相同的项
_rename = dict(filter(lambda (k, v): str(k) != str(v), rename.iteritems()))
#如果原始key不存在,那么新的key对应的值默认为None
#如果新的key已存在于原始key中,那么原始key的值将被新的key的值覆盖
# map(lambda (k, v): fields.setdefault(v, fields.pop(k, None)), _rename.iteritems())
map(lambda (k, v): fields.update({v: fields.pop(k, None)}), _rename.iteritems())
#
return fields
else:
return {}