在 sqlalchemy 中为相同的声明性基础使用不同的模式 [英] Using a different schema for the same declarative Base in sqlalchemy
问题描述
我是 Pyramid 和 SQLAlchemy 的新手.我正在使用 SQLAlchemy 进行 Python Pyramid 项目.我在下面设置了一个简单的模型.我将如何在运行时将其与不同的模式一起使用?这将是一个 PostgreSQL 数据库后端.现在,public"被硬编码到声明性基础模型中.我需要能够使用具有不同模式的相同模型.最好的方法是什么?除非我错过了,否则 SQLAlchemy 的文档对我来说似乎不清楚.
I am new to both Pyramid and SQLAlchemy. I am working on a Python Pyramid project with SQLAlchemy. I have a simple model set up below. How would I go about being able to use this with different schemas at run-time? This will be a PostgreSQL database backend. Right now, "public" is hard-coded into the declarative base model. I would need the ability to use this same model with different schema. What is the best approach? Unless I missed it, the documentation at SQLAlchemy seemed unclear to me.
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
我似乎解决了我的问题,我正在更新代码片段以显示我在下面所做的事情.
I have appeared to solve my issue, I am updating the snippet to show what I did below.
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__
可以减轻这种痛苦.这是 Paul Yin 的回答......
I think you need a different model for each schema. __abstract__
can make this less painful. This follows on to Paul Yin's answer...
定义一个
__abstract__
LoadTender 模型,这样您就不必继续编码了.
Define an
__abstract__
LoadTender model, so you don't have to keep coding it.
#base.py
class LoadTender(Base):
__abstract__ = True
id = ...
def __repr__ ...
在每个架构的层次结构中放置一个特定于架构的 Base.
Put a schema-specific Base in the hierarchy for each schema.
#schema1.py
from base import LoadTender
PublicBase = declarative_base(metadata=MetaData(schema='public'))
class LoadTender(PublicBase, LoadTender):
__tablename__ = 'load_tenders'
对其他架构执行相同操作.
Do the same for other schema.
这篇关于在 sqlalchemy 中为相同的声明性基础使用不同的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!