站点背景图
头像
Tsingten

偶尔记录一点.

首页 » 默认分类 » Alembic - Python数据库迁移工具的使用

Alembic - Python数据库迁移工具的使用

作者: Tsingten 时间: 90天前 评论: 0 条

pip install alembic

首先,我们需要进行初始化

alembic init alembic

这会在工作路径下生成alembic目录以及alembic.ini文件。
在alembic.ini中的sqlalchemy.url配置数据库连接器

元数据的声明

示例代码:

from sqlalchemy import Column, Integer, BigInteger, String, Text, Boolean, Date, DateTime, SmallInteger, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Partition(Base):
    __tablename__ = 'partitions'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    video_count = Column(Integer, default=0)
    
    # 关系
    videos = relationship("Video", back_populates="partition")
    
    def __repr__(self):
        return f"<Partition(name='{self.name}')>"

进入env.py,将target_metadata修改为:
from models import Base
target_metadata = Base.metadata

使用alembic基于元数据自动生成迁移文件:
alembic revision --autogenerate -m "Added table"

应用最新的迁移文件
alembic upgrade head

评论
插入
插入
😀😃😄😁😆😅🤣😂🙂🙃😉😊😇🥰😍🤩😘😗😚😙😋😛😜🤪😝🤑🤗🤭🤫🤔🤐🤨😐😑😶😏😒🙄😬🤥😌😔😪🤤😴😷🤒🤕🤢🤮🤧🥵🥶🥴😵🤯🤠🥳😎🤓🧐😕😟🙁☹️😮😯😲😳🥺😦😧😨😰😥😢😭😱😖😣😞😓😩😫🥱😤😡😠🤬
🖐️