使用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
以生成迁移文件夹。在迁移文件夹中应为空的版本子文件夹、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
将您的更改应用到数据库。