Right now what I am doing is as :
if order_type == 'desc':
result = session.\
query(Customer).\
order_by(desc(getattr(Customer, sorting_column_name))).\
all()
else:
result = session.\
query(Customer).\
order_by(asc(getattr(Customer, sorting_column_name))).\
all()
Is there any way to call order_by
just once and use sorting order provided in order_type
as a variable to decide whether to sort asc
or desc
?
filter() - filter on SQL expressions. method sqlalchemy.orm.Query. first() Return the first result of this Query or None if the result doesn't contain any row.
The second one, filter_by(), may be used only for filtering by something specifically stated - a string or some number value. So it's usable only for category filtering, not for expression filtering. On the other hand filter() allows using comparison expressions (==, <, >, etc.)
c collection is extracted to form a collection of ColumnElement objects. This parameter will also accept TextClause constructs as given, as well as ORM-mapped classes. function sqlalchemy.sql.expression. table(name, *columns, **kw)
Label is a class within the sqlalchemy. sql. elements module of the SQLAlchemy project.
asc
and desc
are just objects, pick one based on the ordering you want:
direction = desc if order_type == 'desc' else asc
result = session.\
query(Customer).\
order_by(direction(getattr(Customer, sorting_column_name))).\
all()
direction
is bound to either asc
or desc
depending on the value of order_type
, then used in building the query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With