我使用Peewee模块作为我项目的ORM.
我看了整篇文档,没有明确的说明
有关如何处理db.execute_sql()的结果的示例.
我跟踪了代码,只能找到db.execute_sql()返回光标.
有谁知道如何处理光标,例如迭代它并获取
从复杂的select语句返回结果.
更新:我刚从peewee文件夹中找到以下源代码,它应该有所帮助
我来解决这个问题.
class QueryResultWrapper(object):
"""
Provides an iterator over the results of a raw Query, additionally doing
two things:
- converts rows from the database into python representations
- ensures that multiple iterations do not result in multiple queries
"""
def __init__(self, model, cursor, meta=None):
self.model = model
self.cursor = cursor
self.__ct = 0
self.__idx = 0
self._result_cache = []
self._populated = False
self._initialized = False
if meta is not None:
self.column_meta, self.join_meta = meta
else:
self.column_meta = self.join_meta = None
def __iter__(self):
self.__idx = 0
if not self._populated:
return self
else:
return iter(self._result_cache)
def process_row(self, row):
return row
def iterate(self):
row = self.cursor.fetchone()
if not row:
self._populated = True
raise StopIteration
elif not self._initialized:
self.initialize(self.cursor.description)
self._initialized = True
return self.process_row(row)
def iterator(self):
while True:
yield self.iterate()
def next(self):
if self.__idx self.__ct):
try:
self.next()
except StopIteration:
break