sqlalchemy - 在 Alembic 迁移中访问模型

标签 sqlalchemy flask-sqlalchemy alembic

我正在将 alembic 迁移用于flask + sqlalchemy 项目,并且在我尝试在 alembic 中查询模型之前,一切都按预期工作。

from models import StoredFile

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('stored_file', sa.Column('mimetype', sa.Unicode(length=32))
    for sf in StoredFile.query.all():
        sf.mimetype = guess_type(sf.title)

上面的代码卡住了添加列,永远不会出来。我猜 StoredFile.query正在尝试使用与 alembic 使用的数据库连接不同的数据库连接。 (但为什么?我在 env.py 中遗漏了什么吗?)

我可以通过使用 op.get_bind().execute(...) 来解决它但问题是如何直接在 alembic 中使用模型?

最佳答案

你不应该使用来自 models 的类在您的 Alembic 迁移中。如果您需要使用模型类,您应该在每个迁移文件中重新定义它们以使迁移独立。原因是可以在一个命令中部署多个迁移,并且可能在编写迁移到实际在生产中执行之间,模型类已根据“稍后”迁移进行了更改。

例如,请参阅 Operations.execute 的文档中的此示例:

from sqlalchemy.sql import table, column
from sqlalchemy import String
from alembic import op

account = table('account',
    column('name', String)
)
op.execute(
    account.update(). \
        where(account.c.name==op.inline_literal('account 1')). \
        values({'name':op.inline_literal('account 2')})
        )

提示:您不需要包含完整的模型类,只需包含迁移所需的部分。

关于sqlalchemy - 在 Alembic 迁移中访问模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17547119/

相关文章:

python - 错误 1273 但我的模式不包含 utf8mb4_0900_ai_ci

python - 应用 alembic 迁移后表序列 id 不增加

python - Alembic --autogenerate 产生空迁移

sql - 使用Flask-SQLAlchemy进行多对多查询

python - 如何删除类似的 alembic 版本?

Python sqlalchemy 尝试使用 .to_sql 将 pandas 数据帧写入 SQL Server

python - 为什么关系中的重复项不违反 UniqueConstraint?

python - 插入时转换数据有问题吗?

python - 在 Flask 中动态创建和持久化模型 - Sqlalchemy

python - 如何在 SQLAlchemy 中嵌套连词 or and 和 _