把SQLAlchemy查询对象转换成字典/json使用(分开)

注:针对的是查询出来的是单条对象

多个对象的话可以使用for循环遍历查询出来的对象列表,也可以使用下面的方法

1.config.py文件

#!/usr/bin/env python
#-*- coding: utf-8 -*-

from sqlalchemy import create_engine,Column,String,Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = '1'
USERNAME = 'root'
PASSWORD = 'root'

DB_URI = "mysql+mysqlconnector://{username}:{password}@{host}:{port}/{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)
engine = create_engine(DB_URI)
Base = declarative_base(engine)
session = sessionmaker(engine)()

class Views(Base):
    __tablename__ = 'views'
    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    ports = Column(String(100))
    
    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict
    db.to_dict = to_dict # 若是使用的flask_sqlalchemy,则改写成: db.to_dict = to_dict
    # 或者使用如下的这种
    #def to_dict(self):
        #return {c.name: getattr(self, c.name) for c in self.__table__.columns}

2.mian.py文件
..........

Info = session.query(Views).filter_by(id=1).first()
Info.to_dict() # 把查询得到的结果转换成字典样式,键是数据表中的字段名,值是数据表中对应的值
..........
针对多个对象的解决方法:
把ORM模型中的to_dict换成如下的:
    def to_dict(self):
        result = {}
        for key in self.__mapper__.c.keys():
            if getattr(self, key) is not None:
                result[key] = str(getattr(self, key))
            else:
                result[key] = getattr(self, key)
        return result

然后再封装一个转换成json的函数:

def to_json(all_vendors):
    v = [ ven.dobule_to_dict() for ven in all_vendors ]
    return v

使用方法:

users = User.query.all()
data = to_json(users)
print(data) # [{'id': '1', 'username': 'admin', 'email': 'admin@example.com'}, {'id': '2', 'username': 'guest', 'email': 'guest@example.com'}]
print(type(data)) # <class 'list'>
print(data[0]) # {'id': '1', 'username': 'admin', 'email': 'admin@example.com'}
print(type(data[0])) # <class 'dict'>

 



 

posted @ 2019-01-04 15:11  哈喽哈喽111111  阅读(3495)  评论(1编辑  收藏  举报