如何在sqlalchemy中为select语句提供列表?

时间:2018-06-12 14:08:00

标签: python sqlalchemy

以下代码适用于选择"国家","性别"来自"消息"哪里〜

    users = session.query(
        Message.country,
        Message.gender,
    ).filter(
        Message.date_joined.between(begin_date, end_date),
    ).all()

当我用这个

尝试sql时
    columns = (
        Message.country,
        Message.gender,
    )

    users = session.query(
        columns
    ).filter(
        Message.date_joined.between(begin_date, end_date),
    ).all()

我收到了错误

sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '(<sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x117f215c8>, <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x117f21518>)'

我想如果我给参数作为元组,那么就有可能存在异常。

如何将列作为查询的变量?

1 个答案:

答案 0 :(得分:1)

列应该是列表的一部分并使用load_only

from sqlalchemy.orm import load_only
columns = ['country', 'gender']

companies = session.query(Message).options(load_only(*columns)).filter(
             Message.date_joined.between(begin_date, end_date)).all()

您也可以尝试with_entities

columns = [Message.country, Message.gender]
companies = session.query(Message).filter(
                 Message.date_joined.between(begin_date, end_date)).with_entities(*columns).all()