You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中用SQLModel关联Tool、User、CountryToolUser并查看底层SQL

关联三张表并添加多条件查询

要关联Tool、User和中间表CountryToolUser,你可以通过多表关联条件构建查询语句,同时叠加多个WHERE筛选条件。以下是具体实现:

1. 编写关联查询逻辑

修改repository.py中的查询函数,把三张表关联起来,并添加自定义筛选条件:

from sqlmodel import select, Session, Depends, or_
from .tables import Tool, User, CountryToolUser
from .database import get_db  # 假设你有获取数据库会话的依赖

def get_tool_user_relations(db: Session = Depends(get_db)):
    # 构建三表关联查询:通过中间表关联Tool和User
    statement = select(Tool, User, CountryToolUser).where(
        # 核心关联条件
        Tool.tool_id == CountryToolUser.tool_id,
        User.user_id == CountryToolUser.user_id,
        # 自定义WHERE条件:多条件默认是AND关系
        User.user_id == 1,
        Tool.tool_name.like("%test%"),
        # 如果需要OR逻辑,用or_()包裹
        or_(Tool.tool_description.is_not(None), Tool.tool_guide.is_not(None))
    )
    # 执行查询并返回结果
    results = db.exec(statement).all()
    return results

关键说明:

  • 多表关联时,直接在where()中传入关联条件,SQLModel会自动处理为JOIN逻辑
  • 自定义筛选条件直接追加到where()参数中,默认是AND逻辑;需OR逻辑时,导入or_()函数包裹对应条件即可

2. 查看后台实际执行的SQL语句

有两种实用方法可以查看最终执行的SQL:

方法一:直接打印查询语句

利用SQLAlchemy的compile()方法,将查询对象转换为带参数的完整SQL字符串:

def get_tool_user_relations(db: Session = Depends(get_db)):
    statement = select(Tool, User, CountryToolUser).where(
        Tool.tool_id == CountryToolUser.tool_id,
        User.user_id == CountryToolUser.user_id,
        User.user_id == 1
    )
    # 打印带参数的完整SQL
    print(statement.compile(compile_kwargs={"literal_binds": True}))
    results = db.exec(statement).all()
    return results
  • literal_binds=True会将参数值直接替换进SQL,方便查看最终执行的完整语句

方法二:开启SQLAlchemy日志

在数据库初始化代码中开启日志,让所有执行的SQL自动输出到控制台:

# 示例database.py中的配置
from sqlmodel import SQLModel, create_engine
import logging

# 配置SQLAlchemy日志级别
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

# 创建引擎时开启echo模式
DATABASE_URL = "sqlite:///./test.db"  # 替换为你的数据库链接
engine = create_engine(DATABASE_URL, echo=True)

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)
  • echo=True会让SQLAlchemy自动输出所有执行的SQL语句、参数和执行耗时,适合开发阶段调试

内容的提问来源于stack exchange,提问作者code_10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:50:28