简体   繁体   English

SQLAlchemy查询动态字段

[英]SQLAlchemy Query Dynamic Field

I have a table with many columns -- 我的桌子上有很多列-

class Dummy(object):
    __tablename__ = 'dummies'
    c1 = Column(Integer)
    c2 = Column(Integer)
    c3 = Column(Integer)
    ...
    cN = Column(Integer)

Can I query through all columns individually without specifying each column name manually? 是否可以在不手动指定每个列名称的情况下单独查询所有列? -- -

for i in range(1, N):
    c_name = 'c%d' % i
    dummy = DBSession().query(Dummy).filter_by(???=0).first()

Thanks. 谢谢。

You can iterate over the columns in a table. 您可以遍历表中的列。 First, the table: 一,表:

from sqlalchemy.orm.attributes import manager_of_class
dummy_table = manager_of_class(Dummy).mapper.mapped_table

and finally, the query 最后,查询

for col in dummy_table.columns:
    dummy = session.query(Dummy).filter(col == 0).first()

Or maybe, you actually are generating a specific set of columns from a more elaborate function than you're showing. 或者,也许实际上是通过比您展示的更加复杂的函数来生成一组特定的列。 In which case, use getattr . 在这种情况下,请使用getattr No, really. 不完全是。

for i in range(1, N):
    c_name = 'c%d' % i
    dummy = DBSession().query(Dummy).filter(getattr(Dummy, c_name) == 0).first()

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

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