请教问题。Flask 中用 SQLAlchemy 查询多表对象未指定列或其中一表未指定列时,如何把查询结果转为 Json
代码片段
# 表 class ProductCheckBillMod(Base): __tablename__ = 'sc_product_check' id = Column(Integer, primary_key=True) bill_no = Column(String) class ProductCheckBillMod(Base): __tablename__ = 'sc_product_check_detail' id = Column(Integer, primary_key=True) # 查询 task_obj = db.session.query(*DBModels).join(*joins).filter(*filters).order_by(*orderbys).slice((page_index - 1) * page_size,page_index * page_size).all()
情况 1 DBModels = [ProductCheckBillMod,ProductCheckBillMod]
情况 2 DBModels = [ProductCheckBillMod.id,ProductCheckBillMod.bill_no,ProductCheckBillMod]
在以上的两种情况下 task_obj 如何转 json
以下这段查询结果转 dict 是 Copy 的,稍微改动过
def queryToDict(models,fsModel=None): if fsModel == None: fsModel = Model if isinstance(fsModel,list): fsModel=fsModel[0] if (isinstance(models, list)): if not len(models): return [] if (isinstance(models[0], fsModel)): lst = [] for model in models: gen = model_to_dict(model) dit = dict((g[0], g[1]) for g in gen) lst.append(dit) return lst else: res = result_to_dict(models) return res else: if (isinstance(models, fsModel)): gen = model_to_dict(models) dit = dict((g[0], g[1]) for g in gen) return dit else: res = dict(zip(models.keys(), models)) find_datetime(res) return res # 当结果为 result 对象列表时,result 有 key()方法 def result_to_dict(results): res = [dict(zip(r.keys(), r)) for r in results] # 这里 r 为一个字典,对象传递直接改变字典属性 for r in res: find_datetime(r) return res def model_to_dict(model): # 这段来自于参考资源 for col in model.__table__.columns: if isinstance(col.type, DateTime): value = convert_datetime(getattr(model, col.name)) elif isinstance(col.type, Numeric): value = float(getattr(model, col.name)) else: value = getattr(model, col.name) yield (col.name, value) def find_datetime(value): pass def convert_datetime(value): pass