这应该是自我解释的。我能够通过Object Relational方法(ORM)公开数据库,但不能通过Declarative方法公开数据库。我没有实例化课程吗?这里缺少的是什么?
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Table, Column, Integer, String
engine = create_engine('my connection details', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
my_table = Table('my_table',
Base.metadata,
autoload=True,
autoload_with=engine,
schema='my_schema')
class MyClass(Base):
__tablename__ = 'my_table'
int_col = Column(Integer, primary_key=True)
str_col = Column(String)
>>> for stuff in session.query(my_table).all():
... print stuff # Works perfectly
>>> for stuff in session.query(MyClass).all():
... print stuff # DatabaseError: table or view does not exist
答案 0 :(得分:1)
试试这个:
class MyClass(Base):
__table__ = my_table
int_col = Column(Integer, primary_key=True)
str_col = Column(String)
声明式为每个映射器创建表,因此声明式中的“my_table”是其他表。 您也可以使用数据库反射:
metadata = sqlalchemy.MetaData(bind=engine)
metadata.reflect()
class MyClass(Base):
__table__ = metadata.tables['my_table']
int_col = Column(Integer, primary_key=True)
str_col = Column(String)