Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns from table in SQLAlchemy

I'm trying to select specific columns from a table like this:

users = Table('users', metadata, autoload=True)
s = users.select([users.c.email])
results = s.execute()
print results

and I'm getting this error:

> Traceback (most recent call last):   File "my_mailer.py", line 35, in
> <module>
>     s = users.select([users.c.email])   File "/task/__pips__/sqlalchemy/sql/selectable.py", line 175, in select
>     return Select([self], whereclause, **params)   File "/task/__pips__/sqlalchemy/sql/selectable.py", line 2082, in __init__
>     self._whereclause = _literal_as_text(whereclause)   File "/task/__pips__/sqlalchemy/sql/elements.py", line 2745, in
> _literal_as_text
>     "SQL expression object or string expected." sqlalchemy.exc.ArgumentError: SQL expression object or string
> expected.

So I tried this:

users = Table('users', metadata, autoload=True)
s = users.select('email')
results = s.execute()
print results

And got this in response:

> Traceback (most recent call last):   File "my_mailer.py", line 36, in
> <module>
>     results = s.execute()   File "/task/__pips__/sqlalchemy/sql/base.py", line 124, in execute
>     return e._execute_clauseelement(self, multiparams, params)   File "/task/__pips__/sqlalchemy/engine/base.py", line 1605, in
> _execute_clauseelement
>     return connection._execute_clauseelement(elem, multiparams, params)   File "/task/__pips__/sqlalchemy/engine/base.py", line 761,
> in _execute_clauseelement
>     compiled_sql, distilled_params   File "/task/__pips__/sqlalchemy/engine/base.py", line 874, in
> _execute_context
>     context)   File "/task/__pips__/sqlalchemy/engine/base.py", line 1023, in _handle_dbapi_exception
>     exc_info   File "/task/__pips__/sqlalchemy/util/compat.py", line 185, in raise_from_cause
>     reraise(type(exception), exception, tb=exc_tb)   File "/task/__pips__/sqlalchemy/engine/base.py", line 867, in
> _execute_context
>     context)   File "/task/__pips__/sqlalchemy/engine/default.py", line 388, in do_execute
>     cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (ProgrammingError) argument of WHERE
> must be type boolean, not type character varying LINE 3: WHERE email

Sure enough, the first argument here is the 'whereclause', not 'columns' like everywhere else, this is reflected in the documentation:

This argument is not present on the form of select() available on Table.

Question: how can I select only specific columns using select on the table? And generally, why on earth the columns argument is not available on select on the table? I can't understand why somebody made the decision to make this different than the standard select.

like image 884
lawicko Avatar asked Jan 30 '14 15:01

lawicko


People also ask

How do I select in SQLAlchemy?

The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.

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.

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.


2 Answers

Use general purpose select instead of Table.select:

stmt = select([users.c.email])
result = conn.execute(stmt) 
like image 127
van Avatar answered Oct 06 '22 20:10

van


With metadata you can do this:

metadata = MetaData(bind=engine)
tblusers = metadata.tables['users']
tblproducts = metadata.tables['products']
# example 1: only columns you want.
data_users = tblusers.select().with_only_columns([tblusers.c.id, tblusers.c.name]).execute()
# example 2: w/ where & order_by
data_products = tblproducts.select().with_only_columns([tblproducts.c.id, tblproducts.c.price, tblproductos.c.description]).where(tblproducts.c.stock > 0).order_by(tblproducts.c.brand).execute()

Be well...

SqlAlchemy Docs

like image 41
Dario Roman Garcia Gonzalez Avatar answered Oct 06 '22 19:10

Dario Roman Garcia Gonzalez