首先,确保您已经安装了必要的依赖项 - SQLAlchemy和Alembic。
在您的项目中,找到alembic.ini文件,并编辑它,以便您的配置正确。配置文件应类似于下面的示例:
[alembic]
script_location = alembic
sqlalchemy.url = postgresql://user:password@localhost:5432/database_name
CREATE SCHEMA new_schema;
from alembic import context
context.configure(
url='postgresql://user:password@localhost:5432/database_name',
target_metadata=target_metadata,
include_schemas=True,
include_schema=new_schema,
)
这样,Alembic就会在迁移脚本中使用新的模式。
from sqlalchemy import create_engine, MetaData, Table, Column, Integer
engine = create_engine('postgresql://user:password@localhost:5432/database_name')
metadata = MetaData(bind=engine, schema='new_schema')
table = Table('my_table', metadata,
Column('id', Integer, primary_key=True),
)
metadata.create_all()
这将创建一个名为my_table的表,并将其放置在新的模式中。
注意:请确保在使用新模式时使用正确的表名和列名。