7

I use mostly SQLAlchemy core(v.1.0.8) expression language with flask(0.12) to create API calls. For a particular case where the table has 20 columns, I wish to select all except 1 particular column. How can this be done in the 'select' clause? Is there anything like 'except' that can be used instead of explicitly selecting the columns by names?

1
  • 1
    I don't think Postgres or SQL in general supports this. But from a performance point of view, there is nothing wrong with just doing select * and then filtering off one column in your presentation layer. Commented Jan 9, 2018 at 5:01

1 Answer 1

6

Normally you'd explicitly name all wanted columns, omitting the column not wanted in the dataset.

stmt = sa.select([MyTable.col1, MyTable.col2, ...])

Notice that the select object accepts a list. So, here it is possible to use list comprehension with an if condition to get the same effect as except:

filt_out = 'col_name_not_wanted'

stmt = sa.select([col for col in MyTable.__table__.columns if col.key != filt_out])

The filter condition can even be another function, and thus you could have more complicated logic.

Example:

def filt(col):
    if col.index:
        return col.primary_key is True
    elif 'secret' in col.key:
        return False
    else:
        return True

stmt = sa.select([col for col in MyTable.__table__.columns if filt(col)])

The above snippet assumes MyTable is a sqlalchemy Declarative Mapping. If instead you have sqlalchemy Table, replace MyTable.__table__ with Mytable

Here's a complete example:

import sqlalchemy as sa
import sqlalchemy.ext.declarative as dec

b = dec.declarative_base()

class M(b):
    __tablename__ = 'm'
    id = sa.Column(sa.Integer, primary_key=True)
    col1 = sa.Column(sa.Integer)

stmt = sa.select([col for col in M.__table__.columns if col.key != 'col1'])
print(stmt)
# prints:
SELECT m.id 
FROM m

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.