如何让Alembic识别SQLModel数据库模型? [英] How to get Alembic to recognise SQLModel database model?

查看:0
本文介绍了如何让Alembic识别SQLModel数据库模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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  

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

这篇关于如何让Alembic识别SQLModel数据库模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆