ssp4599815
9/21/2017 - 8:21 AM

python -- sqlalchemy模型转换

flask-sqlalchemy之 modle转dict

def model_to_dict(model):
    if model is None:
        return
    ret = dict()
    for k in dir(model):
        if k.startswith('_'):
            continue
        v = getattr(model, k)
        if callable(v):
            continue
        if isinstance(v, (datetime.date, datetime.datetime)):
            ret[k] = v.isoformat()
        elif isinstance(v, Decimal):
            ret[k] = str(v)
        else:
            ret[k] = v
    ret.pop('metadata')
    ret.pop('query')
    return ret