问题
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)
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.
回答1:
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)
Or
example = mongo.db.example
details = example.find_one({}, {'name':1, 'lastname':1})
return render_template('blabla.html', details=details)
And your template will be
<tr>
<td>{{ details['name'] }}</td>
<td>{{ details['lastname'] }}</td>
</tr>
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)
Then iterate the list in your template
{% for doc in details}
<tr>
<td>{{ doc['name'] }}</td>
<td>{{ doc['lastname'] }}</td>
</tr>
{% endfor %}
回答2:
Your template would actually have to be more like this:
<tr>
<td>{{ details['name'] }}</td>
<td>{{ details['lastname'] }}</td>
</tr>
No loops.
If you had an array of dictionaries, then you could use your initial template.
来源:https://stackoverflow.com/questions/41739179/flask-mongodb-for-loop-not-working