如何让 Alembic 识别 SQLModel 数据库模型?

How to get Alembic to recognise SQLModel database model?

使用 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 模型一起工作?

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

首先运行alembic init migrations在你的控制台生成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  

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

在这里您可以找到 fastapi-alembic 和 SQLmodel 与异步 PostgreSQL 数据库的集成 https://github.com/jonra1993/fastapi-sqlmodel-alembic