17

我正在使用 Peewee 模块作为我的项目的 ORM。

我阅读了整个文档,没有关于如何处理 db.execute_sql() 的结果的明确示例。

我跟踪了代码,只能找到 db.execute_sql() 返回光标。

有谁知道如何处理游标,例如遍历它并从复杂的 select 语句中取回结果。

更新:我刚刚从 peewee 文件夹中找到了以下源代码,它应该可以帮助我解决这个问题。

类 QueryResultWrapper(对象):
    """
    为原始查询的结果提供一个迭代器,另外还做
    两件事情:
    - 将数据库中的行转换为 python 表示
    - 确保多次迭代不会导致多次查询
    """
    def __init__(self, model, cursor, meta=None):
        self.model = 模型
        self.cursor = 光标

        自我.__ct = 0
        自我.__idx = 0

        self._result_cache = []
        self._populated = False
        self._initialized = False

        如果元不是无:
            self.column_meta,self.join_meta = 元
        别的:
            self.column_meta = self.join_meta = 无

    def __iter__(self):
        自我.__idx = 0

        如果不是 self._populated:
            回归自我
        别的:
            返回迭代器(self._result_cache)

    def process_row(自我,行):
        返回行

    定义迭代(自我):
        行 = self.cursor.fetchone()
        如果不是行:
            self._populated = True
            提高 StopIteration
        elif 不是 self._initialized:
            self.initialize(self.cursor.description)
            self._initialized = True
        返回 self.process_row(row)

    定义迭代器(自我):
        而真:
            产生 self.iterate()

    定义下一个(自我):
        如果 self.__idx self.__ct):
            尝试:
                self.next()
            除了停止迭代:
                休息
4

1 回答 1

32

Peewee 返回一个游标。然后您可以使用 db-api 2 对其进行迭代:

cursor = db.execute_sql('select * from tweets;')
for row in cursor.fetchall():
    print(row)

cursor = db.execute_sql('select count(*) from tweets;')
res = cursor.fetchone()
print('Total: ', res[0])

文件:Database.execute_sql

于 2013-08-29T16:47:21.023 回答