前言
相比于 Django 的 ORM ,SQLAlchemy "不依靠外键进行跨表联查" 的解决方案就比较多。
没啥好说的,只能怪自己学艺不精.. _(:з」∠)_
解决办法
query = database.session().query(models.A, models.B) query = query.join(models.B, models.B.UUID == models.A.UUID).filter(models.a.UUID == '2018061520180621').filter(models.b.xx= 'haha') # 第二个filter可以继续过滤、join 或者删掉..
data = query.all() >>> print ( type(data) ) <class 'sqlalchemy.util._collections.result'> # 然而: # 列表中的项并不是标准的 Python tuple,<class 'sqlalchemy.util._collections.result'>,它是一个 AbstractKeyedTuple 对象,拥有一个 keys() 方法, # 这样可以很容易将其转换成 dict : list = [dict(zip(result.keys(), result)) for result in data] print(jsonify(list))
# 还可以在 filter 得到结果后继续加 join 进行多表联查
按用户名摸糊查询
trans_details.query.join(models.B, models.A.user_id==models.B.id
).filter(Users.username.like('%xx%'))
#select xxx from trans_details inner join trans_details on users.id=trans_details.user_id where users.username like '%xx%'
左外联接(left join),没有内容显示为null
trans_details.query.outerjoin(User).filter(Users.username.like('%xx%')) #select xxx from trans_details left outer join trans_details on users.id=trans_details.user_id where users.username like '%xx%'
神秘代码
from flask import jsonify -- article_view.py @api.route('/get') def get_article(): dic = {"data": []} # 单表查询 # data = db.session.query(models.TbArticle).all() # data = db.session.query(models.TbArticle, models.TbArticleContent) # data.join(models.TbArticle, models.TbArticle.uuid == models.TbArticleContent.uuid) # 另一种诡异的写法,没试过 # results = ( # db.session.query( # Topic.content.label('topic_content'), Reply.content.label('reply_content') # ) # ).select_from(Topic, Reply).filter(Topic.id == Reply.topic_id).paginate(page, per_page) # 上文的写法 query = db.session().query(models.TbArticle, models.TbArticleContent) query = query.join( # 取出所有 models.TbArticleContent, models.TbArticleContent.uuid == models.TbArticle.uuid) # 过滤出 TbArticle.uuid : [tuple] # .filter(models.TbArticle.uuid == '0553857835404640804') # 自定义显示字段:[] # .with_entities( # models.TbArticle.uuid, models.TbArticle.title, models.TbArticleContent.content # ) data = query.all() data_list 数据结构:[{"TbArticle": <TbArticle 2312>, "TbArticleContent": <TbArticleContent 0553857835404640804>},{}] data_list = [dict(zip(result.keys(), result)) for result in data] dic["data"].extend(data_list) print(data_list) # 取出字典中的对象: # for i in data_list: # print(i["TbArticle"].create_time) # print(i["TbArticleContent"].Content) # for obj in data: # # dic["data"].append({"uuid": obj.uuid, "title": obj.title}) # print(type(obj)) # return jsonify(dic) return jsonify("ok") 查询出的结果/对象: # from sqlalchemy.util._collections import result