【问题标题】:How to get Alembic to recognise SQLModel database model?如何让 Alembic 识别 SQLModel 数据库模型?
【发布时间】:2021-10-26 03:15:13
【问题描述】:

使用SQLModel如何让alembic识别下面的模型?

from sqlmodel import Field, SQLModel

class Hero(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None

我一直在研究的一种方法是为 Alembic 导入 SQLalchemy 模型,但查看源代码我找不到如何做到这一点。

如何让 Alembic 与 SQLModel 模型一起工作?

【问题讨论】:

  • “让 alembic 识别下面的模型”是什么意思?几天前我尝试使用 alembic 运行迁移,并且可以识别更改
  • 无论如何我都可以尝试详细说明我是如何做到的。
  • 如果您的更改是可识别的,这就是我所追求的,您可以发布您的解决方案吗?

标签: sqlalchemy fastapi alembic pydantic sqlmodel


【解决方案1】:

Advanced user guide 应该很快就会有关于这方面的信息,而且解释比我的更好,但这是我如何让 Alimbic 迁移工作的。

首先在控制台中运行alembic init migrations 以生成迁移文件夹。 migrations 文件夹内应该是空的 versions 子文件夹、env.py 文件、script.py.mako 文件。 在 script.py.mako 文件中,我们应该在这两行周围的某处添加行 import sqlmodel

#script.py.mako
from alembic import op
import sqlalchemy as sa
import sqlmodel # added

然后我们应该编辑 env.py 文件

#env.py
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

from app.models import * # necessarily to import something from file where your models are stored

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None 
# comment line above and instead of that write
target_metadata = SQLModel.metadata

在写作过程中,您忘记了从 models.py(或存储模型的其他任何地方)导入某些内容。这是主要问题

另外,一个重要的注意事项是通过按 ctrl(CMD) + S 保存模型中的更改 - 这有一些问题。

最后,运行

 alembic revision --autogenerate -m "your message"

应该在 versions 文件夹中生成一个新的 .py 文件,其中包含您的更改。 和

 alembic upgrade head  

将您的更改应用到数据库。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-02-24
  • 2022-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多