在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
Run Code Online (Sandbox Code Playgroud)
这将返回一个类'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
Run Code Online (Sandbox Code Playgroud)
这将返回一个类'sqlalchemy.util._collections.KeyedTuple':('mypassword',)
这是因为查询总是返回一个元组,但逗号会将该元组的元素分配给变量:
>>> foo, bar = (1, 2)
>>> foo
1
>>> bar
2
>>> baz, = (3, )
>>> baz
3
Run Code Online (Sandbox Code Playgroud)
这也适用于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
Run Code Online (Sandbox Code Playgroud)
这被称为"元组拆包"