Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query a table, in sqlalchemy

I know how to query on a model now. Suppose there is a Question model:

class Question(Base):     __tablename__ = "questions"     id=Column(...)     user_id=Column(...)     ... 

Now, I can do:

question = Session.query(Question).filter_by(user_id=123).one() 

But, now, I have a table (not a model) questions:

questions = Table('questions', Base.metadata,                   Column(id, ...),                   Column(user_id, ...),                   ....) 

How to query it as what I do with models?

Session.query(questions).filter_by(user_id=123).one() 

This will report an error:

Traceback (most recent call last): File "<console>", line 1, in <module> File "E:\Python27\lib\site-packages\sqlalchemy-0.6.3-py2.7.egg\sqlalchemy\orm\query.py", line 851, in filter_by   for key, value in kwargs.iteritems()] File "E:\Python27\lib\site-packages\sqlalchemy-0.6.3-py2.7.egg\sqlalchemy\orm\util.py", line 567, in _entity_descriptor     desc = entity.class_manager[key] AttributeError: 'NoneType' object has no attribute 'class_manager' 

But:

Session.query(questions).all() 

is OK.

Is filter_by only work for models? How can I query on tables?

like image 616
Freewind Avatar asked Sep 01 '10 13:09

Freewind


People also ask

How do I query a table in SQLAlchemy?

questions = Table('questions', Base. metadata, Column(id, ...), Column(user_id, ...), ....)

How do I select data in SQLAlchemy?

To select data from a table via SQLAlchemy, you need to build a representation of that table within SQLAlchemy. If Jupyter Notebook's response speed is any indication, that representation isn't filled in (with data from your existing database) until the query is executed. You need Table to build a table.

How does the querying work with SQLAlchemy?

Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

How do I run SQL query from SQLAlchemy in Python?

Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns book_id and book_price. Insert record into the tables using insert() and values() function as shown.


2 Answers

I think it's Session.query(questions).filter(questions.c.user_id==123).one()

like image 173
Jochen Ritzel Avatar answered Sep 22 '22 03:09

Jochen Ritzel


You can query tables that were created with the Table constructor using Session.query(Base.metadata.tables['myTable']).all().

like image 27
Noumenon Avatar answered Sep 20 '22 03:09

Noumenon