Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to create query in sql alchemy filter, but column is(dynamic) in variable/specified in variable.

Original Query:

db_session.query(Notice).filter(Notice.subject.like("%" +query+ "%"))

I want to do query like this:

col_name='subject'
db_session.query(Notice).filter(Notice.col_name.like("%" +query+ "%"))
col_name='status'
status=0
db_session.query(Notice).filter(Notice.col_name != 1)
like image 960
anils Avatar asked Apr 20 '12 18:04

anils


People also ask

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

What is lazy dynamic SQLAlchemy?

lazy = 'dynamic': When querying with lazy = 'dynamic', however, a separate query gets generated for the related object. If you use the same query as 'select', it will return: You can see that it returns a sqlalchemy object instead of the city objects.

What is MetaData in SQLAlchemy?

Metadata contains definitions of tables and associated objects such as index, view, triggers, etc. Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs.


3 Answers

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 + "%")) 
like image 192
van Avatar answered Oct 14 '22 02:10

van


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 + "%")
)
like image 23
Derek 朕會功夫 Avatar answered Oct 14 '22 00:10

Derek 朕會功夫


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)
like image 38
dakes Avatar answered Oct 14 '22 02:10

dakes