Issue
I’m trying to loop through some database rows in a nested loop in Python using peewee. Here’s how I connect to the database and define the model:
from peewee import *
from playhouse.shortcuts import *
db = MySQLDatabase("testdb", **{"host": "localhost", "user": "root", "passwd": ""})
class UserService(Model):
# a primary key of 'id' is implicitly defined
service = CharField()
class Meta:
db_table = "results"
database = db
db.connect()
unique_service_query = UserService.select(UserService.service).group_by(UserService.service)
I’m trying something like this:
for outer_service in unique_service_query:
for inner_service in unique_service_query:
print outer_service.service,inner_service.service
This produced only one item in the outer loop. It looks like the iterators in peewee don’t work the same was as standard list objects. Where/how can I reset the iterator or just return a list?
Solution
I tried out a nested loop like you had and also found that the outer loop only went through one iteration even though the query had multiple results. I don’t know exactly what it is about peewee query results that caused this, but I got the expected result if I first converted the query result to a list like this
list(unique_service_query)
So your code would become
results = list(unique_service_query)
for outer_service in results:
for inner_service in results:
print outer_service.service,inner_service.service
Answered By – ezig
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0