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 Answer
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
select *
and then filtering off one column in your presentation layer.