SqlAlchemy动态在哪里

时间:2014-06-30 00:45:47

标签: python sqlalchemy

我想动态选择我要查询的列,例如:

metadata = MetaData(bind = engine)
booking_table = Table("Bookings",metadata,autoload = True, schema = "SGM")
select_meta = select([booking_table],booking_table.c.event_date==date_string)
conn.execute(select_meta)

会变成这样......

def dynamic_search(field,value):
    booking_table = Table("Bookings",metadata,autoload = True, schema = "SGM")
    select_meta = select([booking_table],booking_table.c.field==value)   #Here are the changes
    conn.execute(select_meta)

由于

1 个答案:

答案 0 :(得分:2)

使用table.c方法,而不是访问get by属性。

>>> from sqlalchemy import MetaData, Table, Integer, Column, create_engine
>>> engine = create_engine('sqlite://')
>>> metadata = MetaData(bind=engine)
>>> table = Table("Bookings", metadata,
...     Column('id', Integer(), primary_key=True,),
...     Column('value', Integer(),),
... )
>>> field = 'value'
>>> table.c.get(field)
Column('value', Integer(), table=<Bookings>)
>>> table.c[field]
Column('value', Integer(), table=<Bookings>)

因此,对于您的示例,代码类似于booking_table.c[field]

记得清理你的输入;你可以查看是否field in table.c

>>> field in table.c
True
>>> 'id' in table.c
True
>>> 'nothere' in table.c
False

Looks like this isn't officially documented,但确实有效。