Python peewee iterate over SelectQuery


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


unique_service_query =

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?


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


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

Leave a Reply

(*) Required, Your email will not be published