2011-07-19 27 views
0

我正在學習SQL鍊金術並通過Expression Language Tutorial。我非常喜歡生成選擇,因爲我可以使用表反射,然後使用Table類方法輕鬆查詢表。這就是我現在正在做的事情來做我想做的事情。選擇具有生成選項的特定列

from sqlalchemy import Table, create_engine, MetaData 
engine = create_engine('mysql://...') 
meta.bind = engine 
table = Table('footable', meta, autoload=True) 

result = table.select().where(...).execute() 

我已經寫了很多選擇,我總是選擇我需要的特定列而不是全選。有沒有辦法指定哪些列在我的SQL鍊金術選擇中返回?

回答

1

在文檔中閱讀select()的更多信息,尤其是關於前兩個參數。
但是下面應該是正確的方向,爲您的工作:

from sqlalchemy.sql import select, and_, or_, not_ 
# ... 
query = select(# what to select (tables or columns) 
       [table.c.column1, table.c.column2], 
       # filters (use any expression using and_, or_, not_... 
       and_(table.c.column1.like("j%")), 
       ) 
result = query.execute() 
+1

我看到,你可以使用選擇對象就像你的例子在這裏所做的。我希望能夠使用Table類提供的select方法選擇列。否則,是的,我知道你可以選擇像你的例子一樣的列。 – jlafay

+2

那麼,'Table.select(...)'只是用'self'作爲參數調用'select(...)':'return select([self],whereclause,** params)''。這意味着你現在不能選擇特定的列。 – van