将sqlalchemy 查询结果转化成json格式
models.py 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, ‘数据获取成功‘)
相关推荐
zhjn0 2020-11-24
夜斗不是神 2020-11-17
学习web前端 2020-11-09
waiwaiLILI 2020-11-03
raidtest 2020-10-09
myccc 2020-09-24
jzlixiao 2020-09-15
guicaizhou 2020-09-15
digwtx 2020-09-14
大秦铁骑 2020-08-19
thatway 2020-08-19
lovecodeblog 2020-08-19
codetyper 2020-08-16
comwayLi 2020-08-16
MongoDB数据库 2020-08-16
cjsyrwt 2020-08-14
Tristahong 2020-08-05
csuzxm000 2020-08-02
前端开发Kingcean 2020-07-30