skellington
skellington

Reputation: 149

SQLAlchemy Sort ColumnCollection

How do I sort a ColumnCollection in SQLAlchemy?

I'm getting a list of columns this way ...

listCols = MyTable.__table__.columns

Now I want to sort the columns by column name but I really don't want to loose the Column class by converting to a OrderedDict.

Upvotes: 0

Views: 629

Answers (2)

mzpq
mzpq

Reputation: 404

@snakecharmerb your solution works great for 1.3 though ColumnCollection has changed with the recent release of SQLAlchemy 1.4.

SQLAlchemy < 1.4

ColumnCollection(*sorted(columns, key=lambda c: c.name))

SQLAlchemy >= 1.4

ColumnCollection(columns=[sorted(columns, key=lambda c: c.name)])

NOTE: I haven't tested on 2.x but I'm guessing that it wants the same as in 1.4

Upvotes: 0

snakecharmerb
snakecharmerb

Reputation: 55600

listCols = MyTable.__table__.columns

returns an ImmutableColumnCollection which is not sortable.

However you could use it to create a new ColumnCollection with the desired order:

from sqlalchemy import sql

new_list_cols = sql.expression.ColumnCollection(*sorted(listCols, key=lambda x: x.name))

Upvotes: 1

Related Questions