在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',)
答案 0 :(得分: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
这称为“元组解包”