在SQL Alchemy(1.0.4)中获取表列

时间:2015-05-14 13:44:57

标签: sqlalchemy

我已经意识到在 SQLAlchemy (v1.0.4)的最新版本中,当使用 table.c.keys()进行选择时,我遇到错误列。

from sqlalchemy import MetaData
from sqlalchemy import (Column, Integer, Table, String, PrimaryKeyConstraint)

metadata = MetaData()

table = Table('test', metadata,
        Column('id', Integer,nullable=False),
        Column('name', String(20)),
        PrimaryKeyConstraint('id')
    )

stmt = select(table.c.keys()).select_from(table).where(table.c.id == 1)

在之前的版本中它曾经工作正常,但现在这会引发以下错误:

sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'id' should be explicitly declared with text('id'), or use column('id') for more specificity.
sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'name' should be explicitly declared with text('name'), or use column('name') for more specificity.

是否有一个函数用于检索所有这些表列而不是使用如下所示的列表推导? [text(x) for x in table.c.keys()]

1 个答案:

答案 0 :(得分:0)

不,但你可以自己动手。

def all_columns(model_or_table, wrap=text):
    table = getattr(model_or_table, '__table__', model_or_table)
    return [wrap(col) for col in table.c.keys()]

然后你会像

一样使用它
stmt = select(all_columns(table)).where(table.c.id == 1)

stmt = select(all_columns(Model)).where(Model.id == 1)

请注意,在大多数情况下,您不需要select_from,即当您实际上没有加入其他表时。