Flask中有多个字段时如何更新记录。蟒蛇

时间:2019-06-21 07:37:19

标签: python flask flask-sqlalchemy

我正在尝试更新sqlite数据库中的记录,即前端查询中的值:

data: [{"cnt_doc":"17","code":"111","contragent":"Name1","contragent_id":2,"created_date":"Mon, 17 Jun 2019 18:54:37 GMT","date_operation":null,"id":2,"rezerv":"23","status":"Status1","status_id":1,"stellag":"67","storage":"NameStorage","storage_id":2,"sum_operation":"100","timestamp":"Mon, 17 Jun 2019 18:54:37 GMT","type":2,"type_id":2,"id_type":0}]

在我的Flask应用程序中,我这样做:

from flask import render_template, flash, redirect, url_for, jsonify, request
from app import app, db
from sqlalchemy.exc import SQLAlchemyError
from app.models import Operation

...

@app.route('/operation', methods=['GET', 'POST'])
def operation():   
        method = request.args.get('method')       
        if method == 'Update':
            data = request.form.get("data")
            try:
                objFormat = json.loads(data)
                for key in objFormat:
                    dict_upd = key

                operat = Operation.query.filter_by(id=int(dict_upd['id'])).first()
                for key in dict_upd.keys():
                    setattr(operat, key, dict_upd[key])

                Operation.query.update(operat)#
                db.session.commit()
                jsonFormat = jsonify(dict_upd)
                dictOut = {"data": dict_upd, "meta": {"success": "true"}}

                return (dictOut)
            except SQLAlchemyError as e:
                return jsonify('Error update record in db', exc_info=e)

就我而言,执行Operation.query.update (operat)时出现错误,我强烈怀疑operat对象是否具有执行更新的必要结构。 当有许多需要更新的字段时,举一个例子或正确的方式来最简洁,正确地更新记录。

以这种形式执行更新记录已成功执行,但结构非常繁琐:

operat = Operation.query.filter_by(id = int(dict_upd['id'])).update(
                                        {'date_operation': dict_upd.date_operation},
                                        {'code': dict_upd.code},
                                        {'status_id': dict_upd.status_id},
                                        {'status': dict_upd.status},
                                        {'type_id': dict_upd.type_id},
                                        {'type': dict_upd.type},
                                        {'storage_id': dict_upd.storage_id},
                                        {'storage': dict_upd.storage},
                                        {'contragent_id': dict_upd.contragent_id},
                                        {'contragent': dict_upd.contragent},
                                        {'sum_operation': dict_upd.sum_operation},
                                        {'rezerv': dict_upd.rezerv},
                                        {'cnt_doc': dict_upd.cnt_doc},
                                        {'stellag': dict_upd.stellag},
                                        )

因此,我正在尝试缩短更新记录的设计。 谢谢。

2 个答案:

答案 0 :(得分:1)

您只需传递字典即可更新功能(docs):

operat = Operation.query.filter_by(id = int(dict_upd['id'])).update(dict_upd)

您还可以使用merge在数据库中创建或更新对象:

operat = db.session.merge(Operation( **dict_upd))

答案 1 :(得分:1)

如果使用操作ID扩展字典,则可以使用SQLAlchemy的bulk_update_mappings来在数据库中更新它们,而ORM的开销很小。我没有很多数字,但是我可以从经验中看出,它将更快,更省力。看看this questionthe documentation

def operation():
  method = request.args.get('method')
  if method == 'Update':
    data = request.form.get("data")
    try:
      objFormat = json.loads(data)
      db.session.bulk_insert_mappings(Operation, objFormat)
      db.session.commit()
      jsonFormat = jsonify(dict_upd)
      dictOut = {"data": dict_upd, "meta": {"success": "true"}}

      return (dictOut)
    except SQLAlchemyError as e:
      return jsonify('Error update record in db', exc_info=e)