Martin Burch
Martin Burch

Reputation: 2921

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

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?

Upvotes: 1

Views: 3479

Answers (2)

Sakib Sakharkar
Sakib Sakharkar

Reputation: 1

you're getting a object in return so use something like this

for outer_service in unique_service_query:
        print(outer_service.your_field_name)

Upvotes: 0

ezig
ezig

Reputation: 1229

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

Upvotes: 3

Related Questions