【问题标题】:Update row using sqlalchemy, marshmallow and flask?使用 sqlalchemy、棉花糖和烧瓶更新行?
【发布时间】:2020-01-29 06:23:00
【问题描述】:

我正在使用烧瓶、sqlalchemy 和棉花糖,我有一个包含数据的表,并且 POST、GET 和 DELETE 工作正常,我在通过将数据作为 JSON 传递来更新整行时遇到问题,我正在查询该行按客户列,尝试了我能找到的所有选项,没有从 JSON 更新数据的真实示例,有什么帮助吗?

db = SQLAlchemy(app)
ma = Marshmallow(app)

class Feedback(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    customer = db.Column(db.String(200), unique=True)
    dealer = db.Column(db.String(200))
    rating = db.Column(db.Integer)
    comments = db.Column(db.Text)

def __init__(self, customer, dealer, rating, comments): 
    self.customer = customer
    self.dealer = dealer
    self.rating = rating
    self.comments = comments

class FeedbackSchema(ma.Schema): 
    class Meta:
        fields = ('id', 'customer', 'dealer', 'rating', 'comments')

feedback_schema = FeedbackSchema()
feedbacks_schema = FeedbackSchema(many=True) 

@app.route('/updateReview', methods=['PUT'])
def updateReview():
    customer = request.args['customer']
    if customer == '':
        return 'Bad request, please enter Customer', 404
    customer = request.json['customer']
    dealer = request.json['dealer']
    rating = request.json['rating']
    comments = request.json['comments']
    update_customer = Feedback(customer, dealer, rating, comments)
    cus = Feedback.query.filter_by(customer=customer).first()
    cus.update(update_customer)
    db.session.commit()
    return 'ok'

【问题讨论】:

  • 错误/输出是什么?该功能是否运行良好但数据库已更新?
  • 我收到 500 服务器错误
  • 你可以使用schema.load(request.get_json(), instance=instance)来更新(用marshmallow sqlalchemy)

标签: flask sqlalchemy marshmallow


【解决方案1】:

问题在于您创建update_customer 的方式以及您尝试更新cus 的方式。

试试这个。

feedback = Feedback.query.filter_by(customer=customer).first()

feedback.customer = customer
feedback.dealer = dealer
feedback.rating = rating
feedback.comments = comments

db.session.add(feedback)
db.session.commit()

【讨论】:

  • 如果我手动更新行中的每个字段,使用 ORM 有什么意义?
  • @guzdo 据我了解,ORM 只负责对象与数据库的交互。它不负责 Object 的当前状态。
猜你喜欢
  • 2020-11-21
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-31
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
相关资源
最近更新 更多