SQLalchemy更新所有行而不是一行 [英] SQLalchemy updating all rows instead of one
本文介绍了SQLalchemy更新所有行而不是一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该代码应用于更新数据库中与"post_id"匹配的帖子.但这会更新表中的每个帖子.
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}}">
推荐答案
您必须检查传递的post_id
与Post
类属性post_id
是否相等.
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))
您的查询应该返回所有Post
记录,因为您使用post_id
本身(而不是使用Post
类属性)检查了post_id
.
Your query should return all the Post
records because you checked post_id
with the post_id
itself (not with the Post
class attribute).
这篇关于SQLalchemy更新所有行而不是一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文