python - MongoDB - Python Flask问题:AttributeError:'Cursor'对象没有属性'title'
问题描述
我正在做一个简单的 Flask-MongoDB CRUD 应用程序,但我不断收到错误消息 AttributeError: 'Cursor' object has no attribute 'title' for my show route。
db = mongo.db
products_collection = db.products
@app.route("/product/<product_title>")
def product(product_title):
product = products_collection.find({"title": product_title})
return render_template('product.html', title=product.title, product=product)
在我的数据库中,产品有一个标题字段。
我相信问题出在“product.title”中,它没有通过产品变量访问标题
解决方案
您需要在产品上定义迭代以从集合中获取文档列表。
@app.route("/product/<product_title>")
def product(product_title):
products = products_collection.find({"title": product_title})
result = []
for i in products :
result.append(i)
p = result[0]
#since result is a list you need to specify index, pay attention to this part, if more
#than one document is retrieved from collection others will be ignored.
return render_template('product.html', title=p.title, product=p)
推荐阅读
- spring-tools-4 - 在 STS 4.0 中忽略未知属性支持缺失
- python - 如何按变量对对象进行分组?
- java - 循环通过特定的小部件
- python - 这是按需设置属性的好习惯(如果在尝试获取属性时不存在)?
- reactjs - 你试图重定向到你当前在 React.js 中的同一条路线
- reactjs - Commonly API call for different components in ReactJS Fetch
- python - 读取大型二进制文件(超过 500 MB)的最快方法?
- javascript - 将图像复制到剪贴板并将图像粘贴到文档编写器时图像变灰
- visual-studio-code - 如何使用推断类型改进 Rust 变量的代码完成?
- firebase - 无法在 Windows 上本地测试 Firebase Cloud Functions:“错误:监听 EACCES”