title: Google Datastore: iterator already started - How to work with these iterators?
body: <p>I get the error &quot;Iterator already started&quot; when using the results of a Datastore query with AppEngine/Flask/Python and would appreciate some help.</p>
  <p>I have a number of users in the Google Datastore, and each user has a 'role' which is a number in the range 0..10.
  When listing the users I want to print &quot;Administrator&quot; for users with role 0, and &quot;User&quot; for all the other users.</p>
  <p>The relevant snippet from the html template file is here:</p>
  <pre><code> {% for each_user in users %}
     &lt;tr&gt;
      &lt;td&gt; &lt;a href=&quot;user_display?find={{each_user.user_id}}&quot; &gt;{{ each_user.user_id}}&lt;/a&gt;&lt;/td&gt;     
      &lt;td&gt; {{ each_user.first_name}} &lt;/td&gt;
      &lt;td&gt; {{ each_user.last_name}} &lt;/td&gt;
      &lt;td&gt; {{ each_user.role}} &lt;/td&gt;   
    &lt;/tr&gt;       
    {% endfor %} 
  </code></pre>
  <p>My first, unlucky attempt is below. It crashes with the error &quot;Iterator already started&quot;. (Note - it might be a bit inaccurate as I lost the original after many changes, but you get the idea).</p>
  <pre><code>q_users = datastore_client.query(kind='user')
  q_users.order = ['first_name']
  users = q_users.fetch()
  
  for item in users:
      if item['role'] == 0:
          item['role'] = &quot;Administrator&quot;
      else:
          item['role'] = &quot;User&quot;
  
  }
  return render_template('users_list.html', users=users) 
  </code></pre>
  <p>Investigating in different places it turns out that the result of a Datastore query is not a list of dictionaries but an iterator object like:</p>
  <pre><code>&lt;google.cloud.datastore.query.Iterator object at 0x.......&gt;
  </code></pre>
  <p>So, as an interim solution, I wrote a loop that walks through the iterator and copies the entities one by one to a list of dictionaries changing the role on the fly.  It works, but the code is ugly and is very impractical:</p>
  <pre><code>q_users = datastore_client.query(kind='user')
  q_users.order = ['first_name']
  users = q_users.fetch()
  
  new_u = []
  # Loop through iterator returned by Datastore
  for u in users:  
      # Assign a string corresponding to the user's role
      if u['role'] == 0: 
          u_role = 'Admin'
      else:
          u_role = 'User'
  
      # Now append to the new list of users
      new_u.append({'user_id': u['user_id'],
                   'first_name': u['first_name'],
                   'last_name': u['last_name'],
                   'role': u_role})
  
  # Send to screen
  return render_template('users_list.html', users=new_u) 
  </code></pre>
  <p>Surely there is a better way. Any suggestions?</p>
  <p>Thanks!</p>