4

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

4

2 回答 2

6

高级用户指南中应该很快就会有关于此的信息,并且解释比我的更好,但这里是我如何使 Alimbic 迁移工作。

首先alembic init migrations在您的控制台中运行以生成迁移文件夹。内部迁移文件夹应该是空版本子文件夹、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"

应该使用您的更改在版本文件夹中生成一个新的 .py 文件。和

 alembic upgrade head  

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

于 2021-09-05T13:30:06.510 回答
0

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

于 2022-02-27T05:01:11.110 回答