I am using the Peewee module as an ORM for my project.
I read all the documentation, there is no clear example on how to process the result from db.execute_sql ().
I traced the code, only you can find db.execute_sql () to return the cursor back.
Does anyone know how to handle the cursor, for example, iterate over it and get the return result from a complex select statement.
Update: I just found the following source code from the peewee folder, it should help me solve this problem.
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
source share