SQLAlchemy - 'Table' object has no attribute '_query_cls' when querying a table obtained with reflect

微笑、不失礼 提交于 2020-12-26 08:42:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!