On Feb 13, 2014, at 6:21 PM, Tony Garcia <tnyr...@gmail.com> wrote: > Hello, > I'm new to SQLAlchemy and have searched high and low for a solution to my > problem so I'm hoping someone here can help. I have a query where I need to > apply the 'order by' clause dynamically (both the column and the direction). > So a 'static' version of my query would be: > > studies = session.query(Study).options( > joinedload(Study.system), > joinedload(Study.site)). > filter(System.system_id=41). > order_by(Study.study_id.desc()). > all() > > However the order can be asc or desc and it could be any column from the 3 > tables. I found this post on Stackoverflow which helps with a dynamic sort > direction (asc, desc), but it doesn't help me with the dynamic column: > > http://stackoverflow.com/questions/20904226/python-sqlalchemy-dynamic-order-by
“dynamic” attribute access in Python is using the getattr() builtin function: def my_query(order_by_column): query = session.query(Study).filter(Study.system_id=41).order_by(getattr(Study, order_by_column)) that seems like what you’re asking, hope it helps.
signature.asc
Description: Message signed with OpenPGP using GPGMail