从数据库SQLAlchemy返回多个字段

2024-04-27 02:44:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这条线:

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

退货:

['first.last@domain.com', 'first.last@domain.com', 'first.last@domain.com', 'first.last@domain.com', 'first.last@domain.com']

我用这个来寻找匹配:

if recipient in used_emails:

如果找到匹配项,我需要从同一行的数据库中提取另一个字段(halo4.c.code)。有什么建议吗?你知道吗


Tags: incomforexecutedbifemaildomain
1条回答
网友
1楼 · 发布于 2024-04-27 02:44:06

我要说的是我的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]

相关问题 更多 >