sqlalchemy对象转dict的示例

781次阅读  |  发布于5年以前

复制代码 代码如下:

def sa_obj_to_dict(obj, filtrate=None, rename=None):
"""
sqlalchemy 对象转为dict
:param filtrate: 过滤的字段
:type filtrate: list or tuple
:param rename: 需要改名的,改名在过滤之后处理, key为原来对象的属性名称,value为需要更改名称
:type rename: dict
:rtype: 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 {}  

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8