mongo cursor could not foreach twice

渲染过程中需要循环从mongo中取出的数据

<div role="tabpanel">
  <!-- Nav tabs -->
  <ul id="tabs" class="nav nav-tabs nav-justified" role="tablist">
    {% for index,i in enumerate(cates) %}
    <li class="{{index == 0 and 'active' or ''}}" role="presentation"><a href="#{{i.get('subtype', None)}}" aria-controls="{{i.get('subtype', None)}    }" role="tab" data-toggle="tab">{{i.get('subtype', None)}}</a></li>
    {% end %}
  </ul>
  
  <!-- Tab panes -->
  <div class="tab-content">
    {% for index,i in enumerate(cates) %}
    <div role="tabpanel" class="tab-pane {{index == 0 and 'active' or ''}}" id="{{i.get('subtype', None)}}">
        <a class="btn btn-default" href="{{ path  }}?act=edit&id={{ str(i['_id']) }}">编辑</a>
        <a class="btn btn-danger" href="{{ path  }}?act=delete&id={{ str(i['_id']) }}">删除</a>
    </div>
    {% end %}
  </div>
</div>

问题是,循环第二次的时候, 没有数据~

从pymongo中返回的数据类型是 pymongo.cursor.Cursor

applist = self.collect.find(query, sort=[('weight', DESCENDING)])
self.render(
        template_name,
        cates=applist,
)

print type(applist)
print applist

<class 'pymongo.cursor.Cursor'>
<pymongo.cursor.Cursor object at 0x7f6a45215d10>

将 cursor 类型转换为 list 类型

applist = self.collect.find(query, sort=[('weight', DESCENDING)])
self.render(
        template_name,
        cates=list(applist),
)

print type(applist)
print applist

<type 'list'>
[{u'_id': ObjectId('5555a9262d250a0b3928bfd0'), u'weight': 99, u'content': [{u'content': [{u'imgid': ObjectId('54957b88ed9c801a75d48ce0'), u'id': ObjectId('54957b88ed9c801a75d48ce2')}, {u'imgid': ObjectId('54069b9ded9c80363d2b3c19'), u'id': ObjectId('54069b9ded9c80363d2b3c1b')}, {u'imgid': ObjectId('5406991bed9c80363d2b3bed'), u'id': ObjectId('5406991bed9c80363d2b3bef')}, {u'imgid': ObjectId('54069798ed9c80363d2b3be3'), u'id': ObjectId('54069798ed9c80363d2b3be5')}], u'name': u'\u5c0f\u5de6\.........

将cursor 对象转换为list类型,解决了这个问题

你可能感兴趣的:(mongo cursor could not foreach twice)