[英]How to alter foreignkey with Alembic
I handle my PostgreSQL migrations with Alembic
.我使用Alembic
处理我的 PostgreSQL 迁移。 This is how I create a table items
:这就是我创建表items
的方式:
from alembic import op
import sqlalchemy as sa
def upgrade():
items_table = op.create_table(
"items",
sa.Column("id", UUID(as_uuid=True), primary_key=True),
sa.Column("user_id", UUID(as_uuid=True), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.ForeignKeyConstraint(
["user_id"],
["users.id"],
),
)
I'd like to make a new migration file to add ondelete="CASCADE"
after the sa.ForeignKeyConstraint(...)
.我想制作一个新的迁移文件以在sa.ForeignKeyConstraint(...)
之后添加ondelete="CASCADE"
。 How can I do this using sqlalchemy
?我怎样才能使用sqlalchemy
做到这一点? How do I drop the ForeignKeyConstraint
and create a new one?如何删除ForeignKeyConstraint
并创建一个新的? Or do I need to drop the whole table and create it again?或者我是否需要删除整个表并重新创建它?
It's something that alembic can actually autogenerate, it would drop current constraint and create a new one.这是 alembic 实际上可以自动生成的东西,它会丢弃当前约束并创建一个新约束。 I have a pretty simple model in this repository我在这个存储库中有一个非常简单的模型
We can add a self referential relationship as an example:我们可以添加一个自引用关系作为例子:
parent_id: Mapped[int] = Column(ForeignKey("book.id"))
def upgrade() -> None:
op.add_column("book", sa.Column("parent_id", sa.Integer(), nullable=True))
op.create_foreign_key(
op.f("fk_book_parent_id_book"), "book", "book", ["parent_id"], ["id"]
)
def downgrade() -> None:
op.drop_constraint(op.f("fk_book_parent_id_book"), "book", type_="foreignkey")
op.drop_column("book", "parent_id")
If we add ondelete="CASCADE"
to it alembic would create new constraint and drop the old one:如果我们将ondelete="CASCADE"
添加到它,alembic 将创建新约束并删除旧约束:
parent_id: Mapped[int] = Column(ForeignKey("book.id", ondelete="CASCADE"))
def upgrade() -> None:
op.drop_constraint("fk_book_parent_id_book", "book", type_="foreignkey")
op.create_foreign_key(
op.f("fk_book_parent_id_book"),
"book",
"book",
["parent_id"],
["id"],
ondelete="CASCADE",
)
def downgrade() -> None:
op.drop_constraint(op.f("fk_book_parent_id_book"), "book", type_="foreignkey")
op.create_foreign_key(
"fk_book_parent_id_book", "book", "book", ["parent_id"], ["id"]
)
You may need to add您可能需要添加
compare_type=True,
compare_server_default=True,
to your context.configure
call in alembic/env.py
, it's covered in alembic documentation到alembic/env.py
中的context.configure
调用,它包含在 alembic 文档中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.