How to give column name dynamically from string variable in sql alchemy filter?

Solution 1:

Just use getattr standard python library function to get an attribute by name:

col_name = 'subject'
db_session.query(Notice).filter(getattr(Notice, col_name).like("%" + query + "%"))

Solution 2:

In newer sqlalchemy version, it should be done this way:

Notice.__table__.c[col_name]

So:

(db_session
    .query(Notice)
    .filter(Notice.__table__.c[col_name].like("%" + query + "%")
)

Solution 3:

I tried @vans solution but it didn't work. I always got an AttributeError complaining that my table didn't have that column. What worked for me was table.columns:

getattr(Notice.columns,col_name)