简体   繁体   English

Python peewee迭代SelectQuery

[英]Python peewee iterate over SelectQuery

I'm trying to loop through some database rows in a nested loop in Python using peewee. 我正在尝试使用peewee在Python的嵌套循环中遍历一些数据库行。 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. 看起来peewee中的迭代器与标准列表对象的工作方式不同。 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 我不知道究竟是什么导致了这个peewee查询结果,但如果我第一次将查询结果转换为这样的列表,我得到了预期的结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM