【问题标题】:MongoDB - Python Flask problem: AttributeError: 'Cursor' object has no attribute 'title'MongoDB - Python Flask问题:AttributeError:'Cursor'对象没有属性'title'
【发布时间】:2020-11-22 20:27:45
【问题描述】:

我正在做一个简单的 Flask-MongoDB CRUD 应用程序,但我不断收到错误消息 AttributeError: 'Cursor' 对象没有我的显示路线的属性'title'。

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

【问题讨论】:

  • 我找到了解决方案!我更改为 find_one 并将 product.title 更改为 product['title] 并且它起作用了!

标签: python mongodb flask


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-11-28
    • 2018-09-23
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2014-11-11
    • 2021-02-08
    • 1970-01-01
    • 2014-04-15
    相关资源
    最近更新 更多