[英]SQLAlchemy Sort ColumnCollection
How do I sort a ColumnCollection in SQLAlchemy?如何对 SQLAlchemy 中的 ColumnCollection 进行排序?
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.现在我想按列名对列进行排序,但我真的不想通过转换为 OrderedDict 来丢失列 class。
listCols = MyTable.__table__.columns
returns an ImmutableColumnCollection
which is not sortable.返回不可排序的ImmutableColumnCollection
。
However you could use it to create a new ColumnCollection with the desired order:但是,您可以使用它来创建具有所需顺序的新ColumnCollection :
from sqlalchemy import sql
new_list_cols = sql.expression.ColumnCollection(*sorted(listCols, key=lambda x: x.name))
@snakecharmerb your solution works great for 1.3 though ColumnCollection
has changed with the recent release of SQLAlchemy 1.4. @snakecharmerb 你的解决方案适用于 1.3,尽管ColumnCollection
已经随着最近发布的 SQLAlchemy 1.4 发生了变化。
ColumnCollection(*sorted(columns, key=lambda c: c.name))
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注意:我没有在 2.x 上测试过,但我猜它想要和 1.4 中的一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.