SQLalchemy按名称查询列

时间:2015-11-24 12:45:06

标签: sqlalchemy

我需要按各种字段值选择多个用户,例如field是列名称的字符串,如'name'或'email':

users = meta.Session.query(User) \
    .filter(User[field].in_(values)) \
    .all()

如何通过名称以编程方式访问列?

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,您可以使用literal_column或标准getattr,请参阅此示例:

from sqlalchemy import create_engine, Column, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.sql.expression import literal_column

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

Base = declarative_base()
session = scoped_session(sessionmaker(bind=engine))

class User(Base):
    __tablename__ = "user"
    login = Column(types.String(50), primary_key=True)
    name = Column(types.String(255))

    def __repr__(self):
        return "User(login=%r, name=%r)" % (self.login, self.name)

Base.metadata.create_all(engine)

if __name__ == '__main__':

    # create two users    
    u1 = User(login='someone', name="Some one")
    u2 = User(login='someuser', name="Some User")
    u3 = User(login='user', name="User")
    u4 = User(login='anotheruser', name="Another User")
    session.add(u1)
    session.add(u2)
    session.add(u3)
    session.add(u4)
    session.commit()

    print "using literal_column"
    print session.query(User).filter(literal_column("login").in_(["someuser", "someone"])).all()

    print "using getattr"
    print session.query(User).filter(getattr(User, "login").in_(["someuser", "someone"])).all()

输出:

using literal_column
[User(login=u'someone', name=u'Some one'), User(login=u'someuser', name=u'Some User')]
using getattr
[User(login=u'someone', name=u'Some one'), User(login=u'someuser', name=u'Some User')]

如果您将使用literal_column,请注意参数已插入查询而不进行任何转换。如果您从应用程序外部接受text参数的值,这可能会使您遇到SQL注入漏洞