2012-11-05 24 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

相關問題