相比於 Django 的 ORM ,SQLAlchemy "不依靠外鍵進行跨表聯查" 的解決方案就比較多。html
沒啥好說的,只能怪本身學藝不精.. _(:з」∠)_ sql
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( ).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%'models.B, models.A.user_id==models.B.id
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%'
神祕代碼json
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