烧瓶MongoDB-For Loop无法正常工作 [英] Flask & MongoDB - For Loop not working

查看:54
本文介绍了烧瓶MongoDB-For Loop无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flask中具有此功能:

Having this for Flask:

example = mongo.db.example
got_name = example.find({'name':1})
got_lastname = example.find({'lastname':1})

details = {'name' : got_name, 'lastname' : got_lastname}

return render_template('blabla.html', details=details)

然后在我的HTML中使用Jinja进行for循环(希望将其作为表):

Then the for loop using Jinja in my HTML (wanting it to be a table):

{% for x in details}
<tr>
    <td>{{ x.['name'] }}</td>
    <td>{{ x.['lastname'] }}</td>
</tr>
{% endfor %}

但是它不起作用,它在我的表中不显示任何内容.我现在在上面写了这个示例,但是我的代码是相似的.

But it won't work, it doesn't display anything in my table. I wrote this example above now, but my code is similar.

推荐答案

您可能要使用 find_one() 返回一个文档,该文档可随后在词典中使用,而不是光标:

You may want to use find_one() instead of find() which returns a cursor to the documents which match the criteria. find_one() returns a single document which can then be used in the dictionary, instead of a cursor:

example = mongo.db.example
doc = example.find_one()

details = { 'name' : doc['name'], 'lastname' : doc['lastname'] }

return render_template('blabla.html', details=details)

example = mongo.db.example
details = example.find_one({}, {'name':1, 'lastname':1})

return render_template('blabla.html', details=details)

您的模板将是

<tr>
    <td>{{ details['name'] }}</td>
    <td>{{ details['lastname'] }}</td>
</tr>


如果要遍历整个集合并返回仅包含 name lastname 字段的文档的列表,则应使用 find() 方法.如果您的数据集相对较小,则以下代码会将整个结果集(游标)转换为列表(所有内容都被拉入内存):


If you want to iterate the whole collection and return a list if documents with just the name and lastname fields, then you should use the find() method. If you have a relatively small dataset, the following code will convert the entire result set (Cursor) into a list (everything is pulled into memory):

example = mongo.db.example
details = list(example.find({}, {'name': 1, 'lastname': 1}))

return render_template('blabla.html', details=details)

然后遍历模板中的列表

{% for doc in details}
<tr>
    <td>{{ doc['name'] }}</td>
    <td>{{ doc['lastname'] }}</td>
</tr>
{% endfor %}

这篇关于烧瓶MongoDB-For Loop无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆