I am using sqlAlchemy SQL Expression Language as follows:
col_name = 'variable_col'
metadata = MetaData(db)
myTable = Table('table_name', metadata,
Column(col_name, Integer))
s = myTable.select()
for rec in conn.execute(s):
What I am trying to accomplish is to order the results desc by the one and only column in the results set.
I tried using the following:
s.order_by(desc(myTable.c))
s.order_by(desc(myTable.c[0]))
I even tried to create a Column object and order by that:
temp_col = Column(col_name, Integer)
s.order_by(desc(temp_col))
All to no avail. The results are returned as if there is no order_by clause.
Any help would be appreciated.
The SQLAlchemy Expression Language presents a system of representing relational database structures and expressions using Python constructs.
In SQLAlchemy, the bindparam() construct has the ability to carry along the actual value that will be ultimately used at expression time.
The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.
from sqlalchemy import create_engine, desc, asc
from sqlalchemy.orm import sessionmaker, Query
# setup the session here...
sort_column = "tables_column_name"
sort_dir = "desc" # or "asc"
sort = asc(sort_column) if sort_dir == "desc" else desc(sort_column)
query = Query([...]).filter(...)
query = query.order_by(sort)
results = session.execute(query).fetchall()
I think this is a more complete answer to dynamically sorting/ordering SQL results.
order_by()
method in SQLAlchemy doesn't modify query it's applied to, but returns a new query. Also columns are accessed by name, not index. Use something like the following:
s = s.order_by(myTable.c[col_name].desc())
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