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?
questions = Table('questions', Base. metadata, Column(id, ...), Column(user_id, ...), ....)
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.
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.
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.
I think it's Session.query(questions).filter(questions.c.user_id==123).one()
You can query tables that were created with the Table constructor using Session.query(Base.metadata.tables['myTable']).all()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With