Alembic迁移,支持多app下的models.py

如果你的项目有多个应用(app),每个应用有自己的 models.py 文件,你可以通过以下步骤来配置 Alembic 以支持这种结构。

假设的项目结构

假设你的项目结构如下:

your_project/
│
├── app1/
│   ├── __init__.py
│   ├── models.py
│   └── ...
│
├── app2/
│   ├── __init__.py
│   ├── models.py
│   └── ...
│
├── core/
│   ├── __init__.py
│   └── base.py
│
├── alembic/
│   ├── versions/
│   └── ...
├── alembic.ini
└── main.py

1. 创建共享的 Base 实例

core/base.py 中创建一个共享的 Base 实例:

# core/base.py

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

2. 修改各个模型文件

确保每个模型文件中的模型都使用同一个 Base 实例:

# app1/models.py

from sqlalchemy import Column, Integer, String
from core.base import Base

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(length=50), unique=True, index=True, nullable=False)
    email = Column(String(length=100), unique=True, index=True, nullable=False)
    password = Column(String(length=100), nullable=False)
# app2/models.py

from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from core.base import Base

class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(length=100), nullable=False)
    content = Column(String(length=1000), nullable=False)
    owner_id = Column(Integer, ForeignKey('users.id'))

    owner = relationship("User", back_populates="posts")

3. 创建一个统一的模型模块

core 目录下创建一个 models.py 文件,用于导入所有应用的模型:

# core/models.py

from app1.models import User
from app2.models import Post

4. 修改 Alembic 配置

编辑 alembic/env.py 文件,使其能够识别所有模型:

# alembic/env.py

from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context

# 导入你的模型并配置目标元数据
from core.base import Base
from core import models  # 确保所有模型都被导入

config = context.config

# Interpret the config file for Python logging.
fileConfig(config.config_file_name)

# add your model's MetaData object here
target_metadata = Base.metadata

def run_migrations_offline():
    """Run migrations in 'offline' mode."""
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url, target_metadata=target_metadata, literal_binds=True
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    """Run migrations in 'online' mode."""
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

5. 生成和应用迁移

生成和应用迁移:

alembic revision --autogenerate -m "Initial migration"
alembic upgrade head

总结

通过上述步骤,你可以在多应用结构的项目中使用 Alembic 进行数据库迁移管理。关键是确保在一个中央位置导入所有模型,并使用同一个 Base 实例,这样 Alembic 就能自动检测到所有模型的更改。具体步骤如下:

  1. 创建一个共享的 Base 实例。
  2. 确保每个模型文件中的模型都使用这个 Base 实例。
  3. 创建一个统一的模型模块,用于导入所有应用的模型。
  4. 配置 Alembic
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值