Jerry
Jerry

Reputation: 2567

SQLAlchemy Query Dynamic Field

I have a table with many columns --

class Dummy(object):
    __tablename__ = 'dummies'
    c1 = Column(Integer)
    c2 = Column(Integer)
    c3 = Column(Integer)
    ...
    cN = Column(Integer)

Can I query through all columns individually without specifying each column name manually? --

for i in range(1, N):
    c_name = 'c%d' % i
    dummy = DBSession().query(Dummy).filter_by(???=0).first()

Thanks.

Upvotes: 1

Views: 1858

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

You can iterate over the columns in a table. First, the table:

from sqlalchemy.orm.attributes import manager_of_class
dummy_table = manager_of_class(Dummy).mapper.mapped_table

and finally, the query

for col in dummy_table.columns:
    dummy = session.query(Dummy).filter(col == 0).first()

Or maybe, you actually are generating a specific set of columns from a more elaborate function than you're showing. In which case, use getattr. No, really.

for i in range(1, N):
    c_name = 'c%d' % i
    dummy = DBSession().query(Dummy).filter(getattr(Dummy, c_name) == 0).first()

Upvotes: 3

Related Questions