繁体   English   中英

在sqlalchemy中为同一声明性Base使用不同的模式

[英]Using a different schema for the same declarative Base in sqlalchemy

我是Pyramid和SQLAlchemy的新手。 我正在使用SQLAlchemy开发Python Pyramid项目。 我有一个简单的模型设置如下。 如何在运行时使用不同的模式? 这将是一个PostgreSQL数据库后端。 现在,“公共”被硬编码到声明性基础模型中。 我需要能够使用不同模式的相同模型。 什么是最好的方法? 除非我错过了,否则SQLAlchemy的文档对我来说似乎不太清楚。

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, BigInteger

    __all__ = [
        "LoadTender"
    ]
    __all__.sort()

    Base = declarative_base()


    class LoadTender(Base):
        __tablename__ = "load_tenders"
        __table_args__ = {"schema": "public"}

        id = Column("pkey", BigInteger, primary_key=True)

        def __repr__(self):
            return "" % self.id

编辑:我似乎解决了我的问题,我正在更新代码片段,以显示我在下面做了什么。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, BigInteger

__all__ = [
    "LoadTender"
]
__all__.sort()

Base = declarative_base()

class ClientMixin(object):
    __table_args__ = {"schema": "client_schema_name"}


class LoadTenderMixin(object):
    __tablename__ = "load_tenders"

    id = Column("pkey", BigInteger, primary_key=True)

    def __repr__(self):
        return "" % self.id


class ClientLoadTender(LoadTenderMixin, ClientMixin, Base):
    pass

我认为每个架构需要一个不同的模型。 __abstract__可以__abstract__痛苦。 接下来是Paul Yin的回答......

  1. 定义__abstract__ LoadTender模型,因此您不必继续编码。

     #base.py class LoadTender(Base): __abstract__ = True id = ... def __repr__ ... 
  2. 在每个模式的层次结构中放置特定于模式的Base。

     #schema1.py from base import LoadTender PublicBase = declarative_base(metadata=MetaData(schema='public')) class LoadTender(PublicBase, LoadTender): __tablename__ = 'load_tenders' 
  3. 对其他架构执行相同操作。

只是一个猜测

LoadTender.__table_args__["schema"] = "whatever"

可能最好把它放在app appigurator创建应用程序的地方

您可以在包模型中使用基本模块

app\
    models\
        base.py
        schema1.py
        schema2.py
    views\
    ...

在base.py中声明Base ,然后将其导入其他模式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM