SQLalchemy updating all rows instead of one

别等时光非礼了梦想. 提交于 2019-12-24 07:40:07

问题


This code is supposed to update a post in the database that matches 'post_id'. But it updates every post in the table.

The code has been edited so it works correctly.

@app.route('/update/<post_id>', methods=['GET', 'POST'])
def update(post_id):
  if 'username' not in session:
    return redirect(url_for('login'))
  post = Post.query.get(post_id)  
  form = PostForm(obj=post)

  if request.method == 'POST':
    if form.validate() == False:
      return render_template('update.html', form=form)
    else:
      Post.query.filter(Post.post_id==int(post_id)).update(dict(
        title=form.title.data, body=form.body.data))
      db.session.commit()
      return redirect(url_for('retrieve'))

  elif request.method == 'GET':
    return render_template('update.html', form=form, post_id=post_id)


class Post(db.Model):
  __tablename__ = 'posts'
  post_id = db.Column(db.Integer, primary_key=True)
  author = db.Column(db.String(128))
  title = db.Column(db.String(128))
  body = db.Column(db.Text)

  def __init__(self, author, title, body):
    self.author = author
    self.title = title
    self.body = body

<form method="POST" action="/update/{{post_id}}">

回答1:


You have to check for equality of passed post_id with the Post class attribute post_id.

Post.query.filter(Post.post_id==int(post_id)).update(dict(
        title=form.title.data, body=form.body.data))

Your query should return all the Post records because you checked post_id with the post_id itself (not with the Post class attribute).



来源:https://stackoverflow.com/questions/42943509/sqlalchemy-updating-all-rows-instead-of-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!