在运行时更改SqlAlchemy声明性模型表模式

时间:2017-10-24 17:01:14

标签: python sqlalchemy

我正在尝试构建一个在postgres和sqlite中运行的声明性表。表之间的唯一区别是postgres表将在特定模式中运行而sqlite表不会。到目前为止,我已经建立了没有使用下面代码的模式构建的表。

metadata = MetaData()

class Base(object):

    __table_args__ = {'schema': None}

Base = declarative_base(cls=Base, metadata=metadata)


class Configuration(Base):
    """
        Object representation of a row in the configuration table
    """

    __tablename__ = 'configuration'

    name = Column(String(90), primary_key=True)
    value = Column(String(256))

    def __init__(self, name="", value=""):
        self.name = name
        self.value = value


def build_tables(conn_str, schema=None):

    global metadata

    engine = create_engine(conn_str, echo=True)

    if schema:
        metadata.schema=schema

    metadata.create_all(engine)

但是,每当我尝试在build_tables()中设置架构时,架构似乎都不会在新构建的表中设置。如果我最初将模式设置为metadata = MetaData(schema='my_project'),我似乎无法工作,直到我知道我将运行哪个数据库。

是否有另一种使用声明性模型动态设置表模式的方法?更改元数据的方法是错误的吗?

0 个答案:

没有答案
相关问题