2013-03-22 122 views
1

我想從表中選擇特定值,由SQLAlchemy的session.py如何動態選擇要在SQLAlchemy中查詢的列?

def query(self, *entities, **kwargs): 
    """Return a new ``Query`` object corresponding to this ``Session``.""" 

    return self._query_cls(entities, self, **kwargs) 
看代碼

它似乎是作爲函數參數,它接受一個元組。所以我所做的就是:

query = ('order', 'location') 
columnsStr = 'order, location' 
table = 'locations' 
sql = "SELECT {0} FROM {1}".format(columnsStr, table) 
data = session.query(query).from_statement(sql).all() 

而且它產生這個錯誤 - InvalidRequestError: SQL expression, column, or mapped entity expected - got '('order', 'location')'

爲什麼不與元組這項工作?

P.S.

如果我改變這些值:

query = 'location' 
columnsStr = 'location' 

我得到一個結果,但僅限於單個列。

回答

3

嘗試

data = session.query('order', 'location').from_statement(sql).all() 

交替,如果你想保持你的元組結構,你可以做這樣的事情

data = session.query(*query).from_statement(sql).all() 

的原因是,當你在一個元組蟒蛇通過,則使該元組到元組

>>> x = (1,2,3) 
>>> def f(*x): 
    print x 
>>> f(x) 
((1, 2, 3),) 
>>> f("location", "order") 
('location', 'order') 
>>> 
+0

這是絕對正確的,謝謝!我最終發現你需要**使用http://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists中的'* argumentsInTuple'語法解開你的參數元組,但是感謝一堆爲答案! – 2013-03-22 17:50:33