首页 > 解决方案 > 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”中,它没有通过产品变量访问标题

标签: pythonmongodbflask

解决方案


您需要在产品上定义迭代以从集合中获取文档列表。

@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)


推荐阅读