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博客

相关推荐
LiLiYuan.4 分钟前
【Lombok库常用注解】
java·开发语言·python
不去幼儿园35 分钟前
【启发式算法】灰狼优化算法(Grey Wolf Optimizer, GWO)详细介绍(Python)
人工智能·python·算法·机器学习·启发式算法
二川bro39 分钟前
数据可视化进阶:Python动态图表制作实战
开发语言·python·信息可视化
青青子衿_211 小时前
TikTok爬取——视频、元数据、一级评论
爬虫·python·selenium
忘却的旋律dw2 小时前
使用LLM模型的tokenizer报错AttributeError: ‘dict‘ object has no attribute ‘model_type‘
人工智能·pytorch·python
20岁30年经验的码农2 小时前
Java RabbitMQ 实战指南
java·开发语言·python
studytosky3 小时前
深度学习理论与实战:MNIST 手写数字分类实战
人工智能·pytorch·python·深度学习·机器学习·分类·matplotlib
上不如老下不如小4 小时前
2025年第七届全国高校计算机能力挑战赛初赛 Python组 编程题汇总
开发语言·python·算法
Q_Q5110082854 小时前
python+django/flask的结合人脸识别和实名认证的校园论坛系统
spring boot·python·django·flask·node.js·php
Q_Q5110082854 小时前
python+django/flask的选课系统与课程评价整合系统
spring boot·python·django·flask·node.js·php