![](/img/trans.png)
[英]Must two SQLAlchemy declarative models share the same declarative_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的回答......
定義__abstract__
LoadTender模型,因此您不必繼續編碼。
#base.py class LoadTender(Base): __abstract__ = True id = ... def __repr__ ...
在每個模式的層次結構中放置特定於模式的Base。
#schema1.py from base import LoadTender PublicBase = declarative_base(metadata=MetaData(schema='public')) class LoadTender(PublicBase, LoadTender): __tablename__ = 'load_tenders'
對其他架構執行相同操作。
只是一個猜測
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.