SQLAlchemy - 带索引的建表语句

标签 sqlalchemy

我正在尝试使用 postgresqlsqalchemy 生成一个 CREATE TABLE 语句。已正确创建列,但缺少索引。

我错过了什么?

这是我正在使用的代码片段...

    table = Table('test', metadata, 
                  Column('id', Integer), 
                  Column('booking', Integer, index=True))
    create_stmt = CreateTable(cls.table).compile(connection)
    print(create_stmt)
    # This print CREATE TABLE test ( id INTEGER, booking INTEGER)
    # Index on column booking is missing

最佳答案

您需要对表的索引使用 CreateIndex

    from sqlalchemy import Table, MetaData
    from sqlalchemy.schema import CreateTable
    
    metadata=MetaData()
    ​
    table = Table('test', metadata, 
                  Column('id', Integer), 
                  Column('booking', Integer, index=True))

    
    create_stmt = CreateTable(table).compile(session.connection())
    print(create_stmt)
    
    CREATE TABLE test (
        id INTEGER, 
        booking INTEGER
    )

    
    from sqlalchemy.schema import CreateIndex
    for index in table.indexes:
        create_stmt2 = CreateIndex(index).compile(session.connection())
        print(create_stmt2)

    CREATE INDEX ix_test_booking ON test (booking)

老实说,这个解决方案不是那么干净而且有点烦人,但我想知道您是否有任何理由不使用完整的模式创建,比如 Base.metadata.create_all(engine).

希望对您有所帮助。

关于SQLAlchemy - 带索引的建表语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33210117/

相关文章:

postgresql - 在 Postgres 中存储固定长度小数组的最佳数据模型(使用 SqlAlchemy)

python - 无法在 sqlalchemy 中引用外键

python - postgres 中的锁定机制/postgres 中的死锁。 [我正在使用 sqlalchemy]

python - 使用 SqlAlchemy 将数据保存到数据库中,对象不可下标

python - SQLAlchemy:触发器不在 INSERT 上触发

python - SQL Alchemy 和 Pyramid 能否处理日期有效场景

python - SQLAlchemy 自动加载插入记录

python - 如何使用 SQLAlchemy 设置 Flask 应用程序进行测试?

python - Flask-Executor 和 Flask-SQLAlchemy : Can't get updated data from DB inside of executor function

python Pandas : export structure only (no rows) of a dataframe to SQL