user3773632
user3773632

Reputation: 495

How to give column list for select statement in sqlalchemy?

below code is for select "country", "gender" from "Message" where ~

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

when I try sql with this

    columns = (
        Message.country,
        Message.gender,
    )

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

I got error

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>)'

I thought if i gave parameter as tuple, would be possible however there was exception.

How can I give columns as variable for query?

Upvotes: 1

Views: 4866

Answers (1)

mad_
mad_

Reputation: 8273

columns should be a part of a list and use 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()

You can also try with_entities

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

Upvotes: 2

Related Questions