2

I have query using SQLAlchemy ORM:

query_category = DBSession.query(Product) \
            .options(defer(Product.stock_qty))\
            .filter(
                Product.categories.any(Category.id == category.id),
                Product.categories.any(Category.id.in_(parent_ids)),
            )

I want to iterate this query in loop twice using for .. in like this:

for i in query_category:
...do something

for i in query_category:
    ...do something else

I understand that this is generator, but i don't know how to 'restart' this generator. I am try to use seek(0) like with file, but it is not work. So what command should i use for restart my query

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
Vladyslav
  • 2,018
  • 4
  • 18
  • 44
  • 1
    could you not do both things while iterating once? is the second iteration dependent on the first one finishing? – omu_negru Aug 17 '17 at 12:54
  • 3
    If you must have 2 separate loops, materialize the results to a list using [`Query.all()`](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.all), [just to avoid some overhead of doing the ORM handling again](https://stackoverflow.com/questions/1078383/sqlalchemy-difference-between-query-and-query-all-in-for-loops). The query object can be iterated over multiple times as is. No need to "restart" it. – Ilja Everilä Aug 17 '17 at 12:55
  • I want to iterate twice, because i want to see that first things in forloop worked fine – Vladyslav Aug 17 '17 at 13:00
  • 2
    Note that iterating over the same query object multiple times will issue the query to the DB each time. All the more reason to use `all()`. – Ilja Everilä Aug 17 '17 at 13:01
  • Thanks this is work fine! – Vladyslav Aug 17 '17 at 14:02
  • @Ilja Everilä, you can write you answer and i will accept it – Vladyslav Sep 28 '17 at 08:40

0 Answers0