binhex
binhex

Reputation: 394

python sqlalchemy dynamic order_by

how can I dynamically set the order by direction based on a variable, as in asc or desc for a sqlalchemy query for a sqlite db?

pseudo code as follows:

sort_order = "asc"

sql_session.query(ResultsDBHistory).order_by(sort_order(ResultsDBHistory.postsize)).limit(max_items_shown)

if I try this it won't accept the string.

Upvotes: 1

Views: 2883

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can access the .asc() or .desc() methods as attributes on ResultsDBHistory.postsize:

order = 'asc'
column_sorted = getattr(ResultsDBHistory.postsize, order)()
sql_session.query(ResultsDBHistory).order_by(column_sorted).limit(max_items_shown)

as columns have asc and desc methods.

Upvotes: 9

Related Questions