简体   繁体   English

使用 SQLAlchemy 检索所有列,但有些列

[英]Retrieving all columns but some with SQLAlchemy

I'm making a WebService that sends specific tables in JSON.我正在制作一个以 JSON 格式发送特定表的 WebService。 I use SQLAlchemy to communicate with the database.我使用 SQLAlchemy 与数据库进行通信。

I'd want to retrieve just the columns the user has the right to see.我只想检索用户有权查看的列。

Is there a way to tell SQLAlchemy to not retrieve some columns ?有没有办法告诉 SQLAlchemy 不检索某些列? It's not correct but something like this :这是不正确的,但像这样:

SELECT * EXCEPT column1 FROM table.

I know it is possible to specify just some columns in the SELECT statement but it's not exactly what I want because I don't know all the table columns.我知道可以在 SELECT 语句中只指定一些列,但这并不是我想要的,因为我不知道所有表列。 I just want all the columns but some.我只想要所有的列,但有一些。

I also tried to get all the columns and delete the column attribute I don't want like this :我还尝试获取所有列并删除我不想要的列属性:

 result = db_session.query(Table).all()
 for row in result:
     row.__delattr(column1)

but it seems SQLAlchemy doesn't allow to do this.但似乎 SQLAlchemy 不允许这样做。 I get the warning :我收到警告:

Warning: Column 'column1' cannot be null 
cursor.execute(statement, parameters)
ok

What would be the most optimized way to do it for you guys ?对你们来说最优化的方法是什么?

Thank you谢谢

You can pass in all columns in the table, except the ones you don't want, to the query method. 您可以将表中的所有列(不包括您不想要的列)传递给查询方法。

session.query(*[c for c in User.__table__.c if c.name != 'password'])

Here is a runnable example: 这是一个可运行的例子:

#!/usr/bin/env python

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import Session


Base = declarative_base()
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

    def __init__(self, name, fullname, password):
        self.name = name
        self.fullname = fullname
        self.password = password

    def __repr__(self):
       return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

engine = create_engine('sqlite:///:memory:', echo=True)

Base.metadata.create_all(engine)
session = Session(bind=engine)
ed_user = User('ed', 'Ed Jones', 'edspassword')
session.add(ed_user)
session.commit()

result = session.query(*[c for c in User.__table__.c if c.name != 'password']).all()
print(result)

You can make the column a defered column. 您可以将列设为延迟列。 This feature allows particular columns of a table be loaded only upon direct access, instead of when the entity is queried using Query. 此功能允许仅在直接访问时加载表的特定列,而不是在使用Query查询实体时加载。

See Deferred Column Loading 请参阅延迟列加载

This worked for me这对我有用

 users = db.query(models.User).filter(models.User.email != current_user.email).all()
 return users

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

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