SQLAlchemy ORDER BY FIELD()

Question:

I am trying to sort an SQLAlchemy ORM object by a field, but with a specific order of the values (which is neither ascending or descending). If I was doing this query on MySQL, it would look like;

SELECT letter FROM alphabet_table WHERE letter in ('g','a','c','k')
ORDER BY FIELDS( letter, 'g','a','c','k');

for the output:

letter
------
  g
  a
  c
  k

For SQLAlchemy, I’ve been trying things along the lines of:

session.query(AlphabetTable).filter(AlphabetTable.letter.in_((‘g’,’a’,’c’,’k’))).order_by(AlphabetTable.letter.in_((‘g’,’a’,’c’,’k’)))

Which doesn’t work… any ideas? It’s a small one-time constant list, and I could just create a table with the order and then join, but that seems like a bit too much.

Asked By: Adam Morris

||

Answers:

This may not be a very satisfying solution, but how about using a case expression instead of order by fields:

sqlalchemy.orm.Query(AlphabetTable) 
    .filter(AlphabetTable.letter.in_("gack")) 
    .order_by(sqlalchemy.sql.expression.case(((AlphabetTable.letter == "g", 1),
                                              (AlphabetTable.letter == "a", 2),
                                              (AlphabetTable.letter == "c", 3),
                                              (AlphabetTable.letter == "k", 4))))

A sqlalchemy func expression can be used to generate the order by field clause:

session.query(AlphabetTable) 
    .filter(AlphabetTable.letter.in_("gack")) 
    .order_by(sqlalchemy.func.field(AlphabetTable.letter, *"gack"))
Answered By: Tim Van Steenburgh

im having a similar issue, the field is in a string format , i want to be able to sort based on a list, if the row’s feild is not in the array id like it to be placed before the other lists , any

Answered By: KEVIN CHRISTOPHER
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.