python type_error ai_generated true

AttributeError: 'AsyncSession' 对象没有属性 'query'

AttributeError: 'AsyncSession' object has no attribute 'query'

ID: python/sqlalchemy-async-session-sync-call

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-08-01首次发现

版本兼容性

版本状态引入弃用备注
1.4.x active
2.0.x active

根因分析

在 AsyncSession 上使用同步会话方法如 session.query();异步会话需要使用可等待的方法。

English

Using synchronous session methods like session.query() on an AsyncSession; async sessions require awaitable methods.

generic

解决方案

  1. 95% 成功率
    Use SQLAlchemy 2.0 style: result = await session.execute(select(User).where(User.id == 1))
  2. 50% 成功率
    For legacy, use AsyncSession with sync_session_factory but that's not recommended.

无效尝试

常见但无效的做法:

  1. 100% 失败

    AsyncSession doesn't have a query method; you must use select().

  2. 90% 失败

    query() is not a coroutine; it doesn't exist.