How to query a table, in sqlalchemy

Question:

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:Python27libsite-packagessqlalchemy-0.6.3-py2.7.eggsqlalchemyormquery.py", line 851, in filter_by
  for key, value in kwargs.iteritems()]
File "E:Python27libsite-packagessqlalchemy-0.6.3-py2.7.eggsqlalchemyormutil.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?

Asked By: Freewind

||

Answers:

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

Answered By: Jochen Ritzel

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

Answered By: Noumenon

This is a bit of a late answer, but what the existing ones are missing is the fact that you can both work with Sessions and with Engines & Connections and that you do not need to work with a Session if you defined sqlalchemy.schema.Table directly.

But when should you use a Session, and when a Connection?

The SQLAlchemy documentation has the following to say regarding this:

Its important to note that when using the SQLAlchemy ORM, these objects [Engines and Connections] are not generally accessed; instead, the Session object is used as the interface to the database. However, for applications that are built around direct usage of textual SQL statements and/or SQL expression constructs without involvement by the ORM’s higher level management services, the Engine and Connection are king (and queen?)

In short:

If you are using the ORM (so you write python classes for you data models), you will work with a Session. If you are directly defining Tables, then you don’t need to involve any ORM (and related management services) and can work directly with a Connection.

So, how would working with a Connection look like?:

Here is a simple example, adapted from the docs about connections that also answers your question about how to query a table:

from sqlalchemy import create_engine
engine = create_engine('postgresql://user:pw@localhost:5432/mydatabase')

# Assuming questions is a sqlalchemy.schema.Table instance

with engine.begin() as connection:
    query = questions.select().where(
        questions.c.user_id == 1)
    q1 = connection.execute(query).fetch_one()
    

See also the docs about sqlalchemy.schema.Table.select for more info.

Answered By: jojo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.