Peewee 如何在使用后重新生成 Select?

Peewee How to regenerate a Select after it has been used?

在 Peewee ORM 中,当一个 Select 对象被迭代时,它变得耗尽并且不能再次使用:

query = Tweet.select()

list(query)  # This executes the SQL

list(query)  # This does not, but will return the same rows that are cached from the first query.

调用 Select.iterator() 无效。我认为迭代器只会阻止结果被缓存,但不会重置游标。

query = Tweet.select()

list(query.iterator())  # Executes SQL

list(query.iterator())  # This raises a pysopg2.InterfaceError: cursor already closed

是否可以重新生成一个 Select 对象以便再次使用它(并对数据库执行后续 SQL),而不是将其包装在 function/duplicating 中select 声明?

是的,你可以使用clone()方法:

query = User.select()
list(query)

query = query.clone()
list(query)  # New execution of query.