python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2025-08-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 60% fail

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

  2. 40% fail

    Changes the result structure.