简体   繁体   English

如何使用SQLAlchemy核心来选择除postgresql中的1个特定列以外的所有表列?

[英]How to use SQLAlchemy core to select all table columns except 1 specific column in postgresql?

I use mostly SQLAlchemy core(v.1.0.8) expression language with flask(0.12) to create API calls. 我主要使用带有烧瓶(0.12)的SQLAlchemy核心(v.1.0.8)表达式语言来创建API调用。 For a particular case where the table has 20 columns, I wish to select all except 1 particular column. 对于表具有20列的特定情况,我希望选择除1个特定列以外的所有内容。 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? 是否可以使用类似“ except”之类的东西来代替按名称显式选择列?

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 : 因此,在这里可以将列表理解与if条件结合使用,以获得与除外相同的效果:

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. 上面的代码段假定MyTable是sqlalchemy声明式映射。 If instead you have sqlalchemy Table, replace MyTable.__table__ with Mytable 如果您有MyTable.__table__ Table, MyTable.__table__替换为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

您可以进行一些聪明的回顾,但是为什么不选择全部而忽略不需要的呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM