Can I dynamically change order_by attributes in my request?

I have the following query:

SearchList = (DBSession.query( func.count(ExtendedCDR.uniqueid).label("CallCount"), func.sum(ExtendedCDR.duration).label("TotalSeconds"), ExtendedCDR,ExtensionMap) .filter(or_(ExtensionMap.exten == ExtendedCDR.extension,ExtensionMap.prev_exten == ExtendedCDR.extension)) .filter(between(ExtendedCDR.start,datebegin,dateend)) .filter(ExtendedCDR.extension.in_(SelectedExtension)) .group_by(ExtendedCDR.extension) .order_by(func.count(ExtendedCDR.uniqueid).desc())) .all() ) 

I would like to be able to define an order_by clause before calling .query (), is this possible?

I tried to do as https://stackoverflow.com/a/237282/ ... suggests for the filter specification, but I had no idea how to create filter_group syntax.

From this post:

 filter_group = list(Column.in_('a','b'),Column.like('%a')) query = query.filter(and_(*filter_group)) 
+4
source share
1 answer

You create an SQL query with a call to DBSession.query() , and this query is not executed until you call .all() on it.

You can save intermediate results and add additional filters or other suggestions if necessary:

 search =DBSession.query( func.count(ExtendedCDR.uniqueid).label("CallCount"), func.sum(ExtendedCDR.duration).label("TotalSeconds"), ExtendedCDR,ExtensionMap) search = search.filter(or_( ExtensionMap.exten == ExtendedCDR.extension, ExtensionMap.prev_exten == ExtendedCDR.extension)) search = search.filter(between(ExtendedCDR.start, datebegin, dateend)) search = search.filter(ExtendedCDR.extension.in_(SelectedExtension)) search = search.group_by(ExtendedCDR.extension) search = search.order_by(func.count(ExtendedCDR.uniqueid).desc()) 

The value you pass to order_by can be created in advance:

 search_order = func.count(ExtendedCDR.uniqueid).desc() 

then used as:

 search = search.order_by(search_order) 

Once your request is complete, get the results by calling .all() :

 SearchList = search.all() 
+4
source

All Articles