2015-05-14 74 views
4

我已經意識到,在SQLAlchemy的(v1.0.4)的最新版本使用table.c.keys()因爲當我收到錯誤選擇列。獲取表列在SQL鍊金術(1.0.4)

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()]

回答

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,即當你實際上並沒有加入一些其他表。

+0

當時我並不知道,但實際上並不需要使用'table.c.keys()'。 這就是我們需要的全部內容:'select([table])' – Ander