当前位置:Gxlcms > 数据库问题 > 将sqlalchemy 查询结果转化成json格式

将sqlalchemy 查询结果转化成json格式

时间:2021-07-01 10:21:17 帮助过:248人阅读

class CompanyGoodsModel(Base): id=Column(Integer, primary_key=True) company_id = Column(Integer) 。。。 #我们在model中定义一个to_json方法,来获取模型的数据 def to_json(self): dict = self.__dict__ if "_sa_instance_state" in dict: del dict["_sa_instance_state"] return dict def get_info_by_id(company_id, category_id): if company_id: data=CompanyGoodsModel.query.filter(CompanyGoodsModel.company_id == company_id).all() return data elif category_id: data = CompanyGoodsModel.query.filter(CompanyGoodsModel.category_id == category_id).all() return data

 

然后在视图层中

@api.route(/company_goods, methods=[GET, POST])
def company_goods():
    if request.method == GET:
        company_id = request.args.get(company_id, ‘‘)
        category_id = request.args.get(category_id, ‘‘)
        data=CompanyGoodsModel.get_info_by_id(company_id, category_id)
        result=[]
        for d in data:
            d.goods_info=eval(d[goods_info])
            result.append(d.to_json())
        if not result:
            return json_response(0001, {}, 数据获取失败 )
        return json_response(0000, result, 数据获取成功)

 

 

将sqlalchemy 查询结果转化成json格式

标签:json格式   company   route   for   base   val   model   app   一个   

人气教程排行