【问题标题】:Update Existing Document : Mongo Alchemy更新现有文档:Mongo Alchemy
【发布时间】:2017-01-17 00:36:18
【问题描述】:

我需要一些有关 MongoAlchemy 的帮助。我正在尝试使用 python、flask、Mongo DM 和 Mongo Alchemy(作为对象文档映射器)创建一个 Web 应用程序,并且我正在努力更新现有文档。

我的问题是我无法通过它的对象 ID 更新现有文档。下面我附上我的 def 以供更新

@app.route('/update', methods =[ 'GET', 'POST' ])    
 def update():
     if request.method == 'POST':
         id = request.form['object_id'] # Getting values with html
         patientzero = BloodDoonor.query.get_or_404(id) 
         first_name = request.form['name']# Getting values with htmlform
         last_name = request.form['surname']# Getting values with html form
         blood_type = request.form['blood_type']# Getting values with html                
         update_record = BloodDoonor.patientzero.update(BloodDoonor.last_name = last_name)
     return render_template('update.html', result = result)

Flask 给了我这个错误:

AttributeError AttributeError: 类型 对象“BloodDoonor”没有属性“patientzero”

我对 Python 很陌生,而且代码不是很好。请原谅我上面给出的草率描述。任何帮助将不胜感激。

【问题讨论】:

  • 试试update_record = patientzero.update(BloodDoonor.last_name = last_name)

标签: flask mongoalchemy


【解决方案1】:

要更新现有文档,只需将您从 db 查询的对象的值更改为表单值,然后保存该对象:

@app.route('/update', methods =[ 'GET', 'POST' ]) 
def update(): 
    if request.method == 'POST':
        id = request.form['object_id']
        patientzero = BloodDoonor.query.get_or_404(id) 
        patientzero.first_name = request.form['name']
        patientzero.last_name = request.form['surname']
        patientzero.blood_type = request.form['blood_type']

        patientzero.save()
    return render_template('update.html')

【讨论】:

  • 当我尝试运行此代码时,Flask 给了我以下错误:UnboundLocalError: local variable 'patientzero' referenced before assignment
  • 我更新了我的答案。错误是关于缩进的。立即尝试
  • 尽情享受吧。干杯;)
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 2015-11-18
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
相关资源
最近更新 更多