How to pass list of columns into query method.

2,843 views
Skip to first unread message

Mayank Soni

unread,
Apr 5, 2017, 6:10:15 AM4/5/17
to sqlalchemy
I am trying to pass list of columns of table into query method using add_columns method. Below i am mentioning code snipped. 
def LLL():
Base = automap_base()
class AAA(Base):
__tablename__ = 'schools_master'
Base.prepare(engine, reflect=True)
session = sessionmaker(bind=engine)
session = session()
col_name = ['dise_code_01','district_name_02','block_name_03','cluster_name_04','village_name_05']
    q = session.query(AAA).add_columns(col_list)
    q = q.limit(100)
    for row in q:
print(row)
When i execute this code it is generating error massage : massage.sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '['dise_code_01', 'district_name_02', 'block_name_03', 'cluster_name_04', 'village_name_05']
Please help me out from this error. 

Simon King

unread,
Apr 5, 2017, 7:38:50 AM4/5/17
to sqlal...@googlegroups.com
add_columns expects each column to be supplied as a separate argument,
so you at least need:

q = session.query(AAA).add_columns(*col_list)

...to unpack the list.

Hope that helps,

Simon

Mayank Soni

unread,
Apr 5, 2017, 8:20:45 AM4/5/17
to sqlalchemy
Thanks Simon for response.
Actually column names I am getting from user interface based on user selection that is why i want pass columns in query method dynamically. can you suggest me how can achieve this.

Mayank Soni

unread,
Apr 5, 2017, 8:27:27 AM4/5/17
to sqlalchemy
Thanks Simon ..........it works 


Simon King

unread,
Apr 5, 2017, 8:51:59 AM4/5/17
to sqlal...@googlegroups.com
If the column names are part of the "schools_master" table, then the
easiest option is something like this:

q = session.query(AAA).limit(100)
for row in q:
for name in col_names:
print '%s = %' % (name, getattr(row, name))

Alternatively:

cols = [getattr(AAA, name) for name in col_names]
q = session.query(*cols).limit(100)
for row in q:
print row

Simon
> --
> SQLAlchemy -
> The Python SQL Toolkit and Object Relational Mapper
>
> http://www.sqlalchemy.org/
>
> To post example code, please provide an MCVE: Minimal, Complete, and
> Verifiable Example. See http://stackoverflow.com/help/mcve for a full
> description.
> ---
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sqlalchemy+...@googlegroups.com.
> To post to this group, send email to sqlal...@googlegroups.com.
> Visit this group at https://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

Mayank Soni

unread,
Apr 5, 2017, 8:56:47 AM4/5/17
to sqlalchemy
Thank you very much .........
 Sure , I will try this
Reply all
Reply to author
Forward
0 new messages