sqlalchemy查询结果转为json并通过restapi接口返回(及输出查询结果)

问题:通过sqlalchemy查询的结果,如果直接通过jsonify函数转为json会报错:

TypeError: Object of type 'Comment' is not JSON serializable,通过filter查询直接输出为<dao.entity.news_material_gather.NewsMaterialCollection object at 0x0000027D31771700>

解决办法:需要在模型类中增加to_json函数

from sqlalchemy import Column, String, Integer, Text, DateTime, func
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class Collection(Base):
    """新闻物料
    """

    # 新闻汇总表
    __tablename__ = 'news_summary'
    index = Column(Integer(), primary_key=True,autoincrement=True)
    collections=Column(Integer())
    read_num=Column(Integer())
    hot_value=Column(Integer())
    
# 新建表press_kit实现写入,比对
    def __init__(self,df):
        self.collections=df.collections
        self.read_num=df.read_num
        self.hot_value=df.hot_value

    def to_json(self):
        dict = self.__dict__
        if "_sa_instance_state" in dict:
            del dict["_sa_instance_state"]
        return dict

将查询的结果,一次通过to_json方法放到数组中,在通过jsonify函数返回到前台或输出:

with self.static_news_session as session:
            news_tables = session.query(Collection).filter(查询条件).all()
        result=[]
        for comment in news_tables:
            result.append(comment.to_json())
            print(result)
return jsonify(result), 200
posted @ 2022-06-12 21:31  KMP  阅读(252)  评论(0编辑  收藏  举报