MongoEngine/mongoengine — pull request #204 by kennu (2012-12-30 17:52:55+00:00)
Title: Fix nested queryset iterations in Django templates and for loops

In Django, you can do this:

articles = Article.objects.all()
for article in articles:
print article.title
for article2 in articles:
print('-', article2.title)

The above code prints out each article, and then also lists all articles underneath it. I use this myself in a Django template (with some additional looping conditions).

In MongoEngine, the same code results in an infinite loop, because the QuerySet does not create new iterator objects, but uses itself as the iterator. So each time the second-level loop finishes, it causes the shared iterator to rewind() itself.

Additionally, when evaluating template variables, Django invokes \_\_call\_\_ on the queryset, which currently resets the query even if it's already iterating. This also causes an infinite loop.

This fix attempts to cover these two issues and includes test cases for both of them. It should not affect top-level loops in any way (it only does things when _iter is already set by the parent iterator).