作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 postgresql
和 sqalchemy
生成一个 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/
我是一名优秀的程序员,十分优秀!