Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: selecting which columns of an object in a query

Is it possible to control which columns are queried in the query method of SQLAlchemy, while still returning instances of the object you are querying (albeit partially populated)?

Or is it necessary for SQLAlchemy to perform a SELECT * to map to an object?

(I do know that querying individual columns is available, but it does not map the result to an object, only to a component of a named tuple).

For example, if the User object has the attributes userid, name, password, and bio, but you want the query to only fill in userid and name for the objects it returns:

# hypothetical syntax, of course: for u in session.query(User.columns[userid, name]).all():     print u 

would print:

<User(1, 'bob', None, None)>  <User(2, 'joe', None, None)> ... 

Is this possible; if so, how?

like image 804
kes Avatar asked Aug 08 '11 04:08

kes


People also ask

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

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 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.

What is SQLAlchemy selectable?

The term “selectable” refers to any object that rows can be selected from; in SQLAlchemy, these objects descend from FromClause and their distinguishing feature is their FromClause.


1 Answers

A simple solution that worked for me was:

users = session.query(User.userid, User.name) for user in users:     print user 

would print:

<User(1, 'bob')>  <User(2, 'joe')> ... 
like image 190
Eli Avatar answered Sep 24 '22 08:09

Eli