问题
I am trying to query a table with SQL Alchemy ORM that I connected to using reflect (it is an existing database). I tried to use the method described here: How to query a table, in sqlalchemy to query the data but I got an error.
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import Session
engine = create_engine(db_uri)
metadata = MetaData(engine)
metadata.reflect()
table = metadata.tables["events"]
Session.query(table).all()
I get the following error:
Traceback (most recent call last):
File "/home/nicolas/anaconda3/envs/chatbot_analytics/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-25-bed7e1c6ef62>", line 1, in <module>
Session.query(tu).first()
File "/home/nicolas/anaconda3/envs/chatbot_analytics/lib/python3.8/site-packages/sqlalchemy/orm/session.py", line 1584, in query
return self._query_cls(entities, self, **kwargs)
AttributeError: 'Table' object has no attribute '_query_cls'
I use version SQLAlchemy==1.3.19. I use a PostgreSQL database.
Is it possible to query the data with the ORM when obtaining the table like this?
回答1:
In
Session.query(table)
you are not calling a method of a Session instance, but passing the Table object as the self argument, because Session is the class, not an instance. The usual way to make a pre-configured session is to use sessionmaker to create a tailored version of the Session class, and then instantiate it:
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
engine = create_engine(db_uri)
metadata = MetaData(engine)
metadata.reflect()
table = metadata.tables["events"]
Session = sessionmaker(bind=engine)
session = Session()
session.query(table).all()
来源:https://stackoverflow.com/questions/63523561/sqlalchemy-table-object-has-no-attribute-query-cls-when-querying-a-table