Flask-SQLAlchemy使用小结

链表查询

join方法允许你指定两个或多个表之间的连接条件,并返回一个新的查询对象,该对象包含了连接后的结果。

内连接

from sqlalchemy import join

使用join函数

query = db.session.query(User, Order).join(Order, User.id == Order.user_id)

results = query.all()

或者使用Query对象的join方法

query = db.session.query(User, Order).join(Order, User.id == Order.user_id)

results = query.all()

遍历结果

for user, order in results:

print(user.username, order.order_id) # 假设Order表有一个order_id字段

左连接

query = db.session.query(User, Order).outerjoin(Order, User.id == Order.user_id)

results = query.all()

遍历结果,注意这里可能有些User没有对应的Order

for user, order in results:

if order is not None:

print(user.username, order.order_id)

else:

print(user.username, "No orders")

通过左连接,查询dialogue_detail和detail_eval表;

复制代码
conditions = [DialogueDetail.dialog_id == dialog_id,
              DialogueDetail.create_by == get_user_id()]
dialog_detail_fields = ["id", "dialog_id", "content", "dialog_role",
                        "user_source", "create_by", "create_time", "is_delete"]
detail_eval_fields = ["comment_type", "feedback_type", "feedback_content"]
query = (db.session.query(*[getattr(DialogueDetail, f1) for f1 in dialog_detail_fields],
                          *[getattr(DialogueDetailEvaluation, f2) for f2 in detail_eval_fields]).
         join(DialogueDetailEvaluation,
              DialogueDetailEvaluation.dialog_detail_id == DialogueDetail.id,
              isouter=True).
         filter(*conditions).order_by(DialogueDetail.create_time))

tmp_all = query.all()

多表连接

假设还有第三个表Product,Order表有一个product_id字段指向Product表的id字段

query = db.session.query(User, Order, Product).join(Order, User.id ==Order.user_id).join(Product, Order.product_id == Product.id)

results = query.all()

遍历结果

for user, order, product in results:

print(user.username, order.order_id, product.name) # 假设Product表有一个name字段

参考:

如何在SQLAlchemy中实现多表联合查询_sqlalchemy 对子查询join-CSDN博客

相关推荐
风逸hhh38 分钟前
python打卡day58@浙大疏锦行
开发语言·python
烛阴1 小时前
一文搞懂 Python 闭包:让你的代码瞬间“高级”起来!
前端·python
JosieBook2 小时前
【Java编程动手学】Java中的数组与集合
java·开发语言·python
Gyoku Mint3 小时前
深度学习×第4卷:Pytorch实战——她第一次用张量去拟合你的轨迹
人工智能·pytorch·python·深度学习·神经网络·算法·聚类
郭庆汝8 小时前
pytorch、torchvision与python版本对应关系
人工智能·pytorch·python
思则变11 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
漫谈网络12 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
try2find13 小时前
安装llama-cpp-python踩坑记
开发语言·python·llama
博观而约取14 小时前
Django ORM 1. 创建模型(Model)
数据库·python·django
精灵vector16 小时前
构建专家级SQL Agent交互
python·aigc·ai编程