Python 如何让Sqlalchemy在它生成的sql中保持列顺序?

Python 如何让Sqlalchemy在它生成的sql中保持列顺序?,python,sqlalchemy,Python,Sqlalchemy,Sqlalchemy在为表生成sql时似乎并没有保留列顺序。如何让sqlalchemy使用与列定义相同的顺序 例如: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Table, MetaData, Column, BigInteger, Integer, String, MetaData, ForeignKey, Date, DateTime from sqlalchemy impo

Sqlalchemy在为表生成sql时似乎并没有保留列顺序。如何让sqlalchemy使用与列定义相同的顺序

例如:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Table, MetaData, Column, BigInteger, Integer, String, MetaData, ForeignKey, Date, DateTime

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()


class MyTable(Base):
    __tablename__ = "my_table"

    id = Column(BigInteger, primary_key=True)
    col1 = Column(String(20), name="col1")
    col2 = Column(Integer)
    col3 = Column(BigInteger, name="col_3")

engine = create_engine('sqlite:///foo.db')
Session = sessionmaker(engine)
db = Session()

print(db.query(MyTable).statement.compile(engine))
输出为:

SELECT my_table.col_3, my_table.id, my_table.col1, my_table.col2
FROM my_table
而不是

SELECT my_table.id, my_table.col1, my_table.col2, my_table.col_3
FROM my_table
Sqlalchemy似乎在表定义中保留了列顺序,因为当它生成CREATETABLE命令时,列顺序与列定义的顺序相匹配

from sqlalchemy.schema import CreateTable
print(CreateTable(MyTable.__table__).compile(engine))

这些列在映射器中的存储方式与在表中的存储方式不同。当你做
CreateTable(MyTable.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。当您执行
session.query(MyTable)
it时<代码>\u props
的填充方式与
列的填充方式不同,并且由于SQLAlchemy内部的某些决定,这可能导致不同的顺序

答案最终是否定的,您无法保证查询列的顺序,因为在幕后还有其他力量在起作用。若秩序对你们来说真的很重要,那个么它可能会反对炼金术


在这种情况下,指定与属性名不匹配的列名会更改列在内部的存储顺序。从该列中删除
name='col_3'
将“修复”此问题。

这有点可笑,但如果将col_3更改为col3,它将按声明的方式发出列

为什么呢

执行映射器配置时,会出现以下注释

        # look through columns in the current mapper that
        # are keyed to a propname different than the colname
        # (if names were the same, we'd have popped it out above,
        # in which case the mapper makes this combination).
        # See if the superclass has a similar column property.
        # If so, join them together.

您的col_3将转到mapper类的properties参数,该参数将用作可选类的第一个参数。

您能否澄清您正在查看的文件,以及如何修改它以按声明的顺序获取列?declarative/base.py和orm/mapper.py。更改列的名称(列(名称=…)以匹配属性名称。