SQLAlchemy - 在对象中执行搜索词结果

SQLAlchemy - execution of search term results in object

我正在对我的会话执行搜索词并将结果集合保存在 'sw' 中。 然后,对于每场比赛,我都想打印匹配的联系人,但我得到的是一个对象。我花了几天时间试图四处寻找并访问对象内部的信息,但到目前为止我的研究技能让我失望了。

如果有人能告诉我我缺少什么,那会有所帮助。

最终我希望能够调用搜索词,然后为每个结果填充一个 ui 元素,因此我需要能够访问匹配联系人的属性,例如帐户、fName 、电子邮件等。

我的代码:


        term = select([Contacts]).where((Contacts.account == skey) | (Contacts.fName == skey) |
                                        (Contacts.lName == skey) | (Contacts.phone == skey) | (Contacts.address == skey) |
                                        (Contacts.company == skey) | (Contacts.email == skey))
        sw = session.execute(term)

        if option == '0':
            print(f'0 - Search session,  Search Key: \'{skey}\'')

            if sw:
                for contact in sw:
                    print(f"Contact match: {contact}")

问题在输出中很明显。 联系人对象。我试过 help().__dict__ 等,但我无法访问联系人不同的信息字段。

我也试过contact.email这样的.notation,但是报错:

Exception has occurred: AttributeError
Could not locate column in row for column 'email'

我的输出:

0 - Search session,  Search Key: 'T'
Contact match: (<__main__.Contacts object at 0x000001906B3DA3D0>,)

您的查询结果 sw 是 SQLAlchemy Row 对象的迭代器。当您遍历 sw 并打印 contact 时,您实际上是在打印这些 Row 对象,这是您看到的包含 ORM 对象的元组。

要直接取回 ORM 对象列表(而不是 Row 个对象),请使用 scalars() 方法:

sw = session.execute(term).scalars().all()

在 SQLAlchemy 中阅读更多内容 documentation:

When selecting a list of single-element rows containing ORM entities, it is typical to skip the generation of Row objects and instead receive ORM entities directly, which is achieved using the Result.scalars() method

你还有一个问题 - Python 不知道如何打印你的 Contacts ORM 对象,所以它只是默认打印它的名称和内存地址(如你所见) .要纠正这个问题,您可以在 ORM class 上定义一个 __repr__ 魔术方法。这允许您定义 Python 如何计算对象的字符串表示形式。你的情况是这样的:

class Contacts(Base):
    ...

    def __repr__(self):
        return f"{self.fName} {self.lName}"

在 Python 的文档 here 中阅读有关 __repr__ 的更多信息。