Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over ResultProxy many times?

Suppose I execute the following query:

results = db.engine.execute(sql_query)

where it returns rows as expected:

>>> for record in results:
...     print(record['path'])
... 
Top.Collections.Pictures.Astronomy.Stars
Top.Collections.Pictures.Astronomy.Galaxies
Top.Collections.Pictures.Astronomy.Astronauts

When I try to iterate over it a second or third time the object is empty:

>>> for record in results:
...     print(record['path'])
...
>>> 

How can I save and reuse the ResultProxy to iterate over it many times?

like image 589
JZ. Avatar asked Mar 10 '23 23:03

JZ.


1 Answers

You probably have an iterator object being returned, so once it's exhausted after iterating over it, you can't go over it again. Assuming your results are not extremely large, you can do:

results = db.engine.execute(sql_query) 
results = list(results)

That turns the iterator object into a list and you can iterate over it as many times as you would.

like image 142
Moses Koledoye Avatar answered Mar 19 '23 08:03

Moses Koledoye