我正在使用process_revision_directives对引用模式生成的操作进行一些后处理。我坚持的一个问题是从说明中删除 postgres 架构,因此可以使用 another question 中的答案在运行时一般更改它。 .
以下代码正确地从 CreateTableOp
中除 ForeignKeyConstraints
之外的操作中删除架构。
def process_foreign_key(col: sa.ForeignKeyConstraint):
col.referred_table.schema = None # Doesn't work
def process_revision_directives(context, revision, directives):
# Remove the schema from the generated operations
for op in chain(directives[0].upgrade_ops.ops, directives[0].downgrade_ops.ops):
if isinstance(op, ops.CreateTableOp):
op.columns = [
process_foreign_key(col) if isinstance(col, sa.ForeignKeyConstraint) else col
for col in op.columns
]
op.schema = None
当前生成的输出如下
op.create_table('user',
sa.Column('id', sa.Integer, nullable=False),
sa.ForeignKeyConstraint(['id'], ['reference_schema.group.id'], name='group_group_id', onupdate='CASCADE', ondelete='CASCADE'),
)
关于如何修改这些约束对象以使目标表中没有 reference_schema.
有什么想法吗?
最佳答案
如果您查看渲染链,您可以找到最后一个架构引用的位置。它位于 op._orig_table
上,但重要的是它在该表上出现了两次。
将以下内容放入 for
循环中。
op._orig_table.schema = None
op._orig_table = op._orig_table.tometadata(clear_meta)
其中clear_meta
是一个没有架构的MetaData
对象,例如
clear_meta = sa.MetaData(bind=session.connection(), schema=None)
关于python-3.x - 在 Alembic 后处理中修改foreignkeyconstraint模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660181/