Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy:将表反射到显式创建的类中_Python_Database_Postgresql_Orm_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy:将表反射到显式创建的类中

Python SQLAlchemy:将表反射到显式创建的类中,python,database,postgresql,orm,sqlalchemy,Python,Database,Postgresql,Orm,Sqlalchemy,假设在一个PostgreSQL数据库中有两个模式,每个模式包含同名的表。例如:schema1.table、schema2.table 我使用SQLAlchemy处理数据库 第一个问题是,我无法将指定具体模式的数据库中的表反映到显式创建的类中。例如: from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative

假设在一个PostgreSQL数据库中有两个模式,每个模式包含同名的表。例如:schema1.table、schema2.table

我使用SQLAlchemy处理数据库

第一个问题是,我无法将指定具体模式的数据库中的表反映到显式创建的类中。例如:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import DeferredReflection

Base = declarative_base()

class Table(DeferredReflection, Base):
    __tablename__ = 'table'

## somehow specify schema for table

engine = create_engine(
    'postgresql+psycopg2://localhost/postgres',
    isolation_level='READ UNCOMMITTED'
)

DeferredReflection.prepare(engine)

## do something using reflected table
第二个问题是,我正在寻找一种方法,将显式创建的类与来自不同模式的表绑定,并按如下方式使用它:

session = Session()
with schema_context('schema1'):
    data = session.query(Table).all()  # Table refers to schema1.table 
    ...

with schema_context('schema2'):
    data = session.query(Table).all() # Table refers to schema2.table
    ...

有什么方法可以解决所描述的问题吗?

SQLAlchemy
对象允许您传递消息

使用声明式,参数通过
\uuuu Table\u args\uuuu
传递到底层的
对象,如下所示

必须为不同的架构创建单独的表

class MyTable(DeferredReflection, Base):
    __tablename__ = 'my_table'
    __table_args__ = {'schema': 'schema2'}