2013-03-07 21 views
0

在SQLAlchemy中,如果您在查詢中加上一個逗號,如下圖所示,你會得到一個「串」回來。如果你不用逗號,你會得到一個元組。爲什麼如此?我看不到任何地方在文檔SQLAlchemy的:它是如何,一個逗號確定如果查詢返回一個字符串或一個元組?

在解釋使用SQLAlchemy0.8下面

代碼返回一個字符串

def get_password(self, member_id): 
    for password, in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id): 
     return password 

這會返回一個類 'STR''mypassword'

儘管以下代碼返回的元組;

def get_password(self, member_id): 
    for password in session.query(Member.__table__.c.password).filter(self.__table__.c.id == member_id): 
     return password 

這會返回一個類的sqlalchemy.util._collections.KeyedTuple'('mypassword',)

回答

5

這是因爲查詢總是返回一個元組,而是逗號是元組的元素分配給變量:

>>> foo, bar = (1, 2) 
>>> foo 
1 
>>> bar 
2 
>>> baz, = (3,) 
>>> baz 
3 

而且這也適用於for循環:

>>> for a, b in [(1, 'x'), (2, 'y')]: 
...  print a, "and b is", b 
... 
1 and b is x 
2 and b is y 

這被稱爲 「元組拆包」

相關問題