SQLAlchemy object to dict example _python

Source: Internet
Author: User

Copy Code code as follows:

def sa_obj_to_dict (obj, Filtrate=none, Rename=none):
"""
SQLAlchemy object to Dict
:p Aram filtrate: Filtered Fields
: Type filtrate:list or tuple
:p Aram Rename: Need to rename, renamed after filtering processing, key for the original object's property name, value is required to change the name
: Type Rename:dict
: rtype:dict
"""

If Isinstance (obj.__class__, Declarativemeta):
# an SQLAlchemy class
#该类的相关类型, i.e. direct and indirect parent 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不存在, then the new key corresponds to the default value of None
#如果新的key已存在于原始key中, the value of the original key will be overwritten by the value of the new 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 {}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.