Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Order By Clause using sqlAlchemy's SQL Expression Language

Tags:

sqlalchemy

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.

like image 488
Ray Avatar asked May 03 '11 19:05

Ray


People also ask

Is SQLAlchemy a language?

The SQLAlchemy Expression Language presents a system of representing relational database structures and expressions using Python constructs.

What is Bindparam SQLAlchemy?

In SQLAlchemy, the bindparam() construct has the ability to carry along the actual value that will be ultimately used at expression time.

What is subquery in SQLAlchemy?

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.

How do I run a SQLAlchemy query?

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.


2 Answers

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.

like image 180
CubeBot88 Avatar answered Oct 17 '22 10:10

CubeBot88


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())
like image 32
Denis Otkidach Avatar answered Oct 17 '22 11:10

Denis Otkidach