python runtime_error ai_generated true

查询已定义标签,但正在迭代结果。请使用 .all() 或 .first()

sqlalchemy.exc.InvalidRequestError: Query has been defined with a label, but the result is being iterated over. Use .all() or .first()

ID: python/sqlalchemy-query-corrupted-during-iteration

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

版本兼容性

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

根因分析

尝试迭代已配置列标签的 Query 对象,不允许直接迭代。

English

Trying to iterate over a Query object that has been configured with a column label, which is not allowed directly.

generic

解决方案

  1. 100% 成功率
    result = session.query(User.name.label('username')).all()
    for row in result:
        print(row.username)

无效尝试

常见但无效的做法:

  1. 60% 失败

    May still raise the same error because the query is already labeled.

  2. 40% 失败

    Changes the result structure.