2012-11-05 22 views
1

这条线:返回不止一个字段从数据库SQLAlchemy的

used_emails = [row.email for row 
      in db.execute(select([halo4.c.email], halo4.c.email!=''))] 

返回:

['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'] 

我用它来寻找匹配:

if recipient in used_emails: 

如果找到匹配我需要从同一行的数据库中拉出另一个字段(halo4.c.code)。有关如何做到这一点的任何建议?

回答

0

我会告诉你说我的SQLAlchemy体验是有限的(所以,如果这是基础的道歉),但是当你得到你的结果,创建一个字典(而不是一个列表)是可行的,键入通过email,其值代表该行中的所有数据(SELECT *)?这样,如果您找到了匹配的电子邮件,则可以参考该密钥的值并提取所需的数据(即halo4.c.code)。这会为您节省另一个数据库,因为该值将存在于您的字典中。

在Python 2.7,是这样的:

used_emails = {row.email: row.code for row in select([halo4.c.email, halo4.c.code], halo4.c.email != '')} 

或者在Python 2.6:

used_emails = dict(
    (row.email, row.code) for row in db.execute(
     select([halo4.c.email, halo4.c.code]halo4.c.email!=''))) 

然后,您可以使用类似:

if recipient in used_emails: 
    # This may not be the proper syntax - happy to troubleshoot if not 
    print used_emails[recipient] 
+0

似乎是个好主意。它出错了,并说'[row.email:'中的':'是'SyntaxError:invalid syntax'。 –

+0

这是与'['而不是'{'。当我将其切换回你提示的方式时,它说'row for'中的'for'是'SyntaxError:invalid syntax' –

+0

@DavidNeudorfer Python 2.6有什么可能吗?我会更新一些与之相关的东西。 – RocketDonkey

相关问题