Example of converting sqlalchemy object to dict

Source: Internet
Author: User

Copy codeThe Code is as follows:
Def sa_obj_to_dict (obj, filtrate = None, rename = None ):
"""
Convert sqlalchemy object to dict
: Param filtrate: filtered Field
: Type filtrate: list or tuple
: Param rename: name to be renamed. The name is processed after filtering, the key is the attribute name of the original object, and the value is the name to be changed.
: Type rename: dict
: Rtype: dict
"""

If isinstance (obj. _ class __, DeclarativeMeta ):
# An SQLAlchemy class
# Related types of this class, that is, direct and indirect parent classes
Linoleic = obj. _ class _. _ mro __
# Filter unwanted parent classes
Linoleic = filter (lambda c: hasattr (c, '_ table _'), filter (lambda c: isinstance (c, DeclarativeMeta ))
Columns = []
Map (lambda c: columns. extend (c. _ table _. columns), linoleic [:-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 ):
# First remove items with the same key and value
_ Rename = dict (filter (lambda (k, v): str (k )! = Str (v), rename. iteritems ()))
# If the original key does not exist, the default value of the new key is None.
# If the new key already exists in the original key, the original key value will be overwritten by the new key value.
# 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.