Home > Backend Development > Python Tutorial > Detailed explanation of examples of sqlalchemy in js

Detailed explanation of examples of sqlalchemy in js

零下一度
Release: 2017-07-20 20:17:35
Original
2012 people have browsed it

There are mostly two return types of sqlalchemy, one is Model object, and the other is Query collection (only query some fields).

For these two return results, they are all from the same type sqlalchemy.orm.query.Query

So we do the corresponding processing for Query and let it return a dict

class AlchemyJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        # 判断是否是Query
        if isinstance(obj, Query):
            # 定义一个字典数组
            fields = []
            # 定义一个字典对象
            record = {}
            # 检索结果集的行记录
            for rec in obj.all():
                # 检索记录中的成员
                for field in [x for x in dir(rec) if
                              # 过滤属性
                              not x.startswith('_')
                              # 过滤掉方法属性
                              and hasattr(rec.__getattribute__(x), '__call__') == False
                              # 过滤掉不需要的属性
                              and x != 'metadata']:
                    data = rec.__getattribute__(field)
                    try:
                        record[field] = data
                    except TypeError:
                        record[field] = None
                fields.append(record)
            # 返回字典数组
            return fields
        # 其他类型的数据按照默认的方式序列化成JSON
        return json.JSONEncoder.default(self, obj)
Copy after login

 

This way you can simply use

json.dumps(result1, cls=AlchemyJsonEncoder)
Copy after login

every time you serialize it. The json of the result set is serialized.

The above is the detailed content of Detailed explanation of examples of sqlalchemy in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template