使用数据库中预先存在的数据编辑SelectMultipleField



我正在构建一个烧瓶应用程序。我有帖子和标签。在发布帖子时,可以为帖子选择许多标签(就像这里的堆栈溢出一样(。现在的问题在于帖子的编辑位置。由于存在预先存在的值,由于重复的条目,我得到了sqlalchemy.exc.IntegrityError。在提交到数据库之前,我已经尝试删除重复的条目

post.tags = list(set(post.tags.all()))

但它仍然会带来同样的错误。以下是编辑帖子的查看功能:

@home.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_post(id):
post = Post.query.get_or_404(id)
if current_user != post.author and not current_user.can(Permission.ADMINISTER):
abort(403)
form = PostForm()
form.tag.choices = [(tag.id, tag.name) for tag in Tag.query.order_by('name')]
if form.validate_on_submit():
post.body = form.body.data
for id in form.tag.data:
post.tags.append(Tag.query.get(id))
db.session.commit()
return redirect(url_for('.view_post', id=post.id))
form.body.data = post.body
form.tag.choices = [(tag.id, tag.name) for tag in Tag.query.order_by('name')]
form.tag.data = post.tags.all()
return render_template('home/edit_post.html', form=form, title='Edit Post')

请帮我解决这个问题,或者给我一个更好的逻辑建议。把我当作一个初学者。

经过多次尝试,我成功地实现了编辑。因此,首先我用post-id(返回元组列表(例如[(62,1(,(62,4(]来查询这个表中的所有类别。元组是(post_id,tag_id(。

categories = db.Table('categories', db.Column('post_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True), db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'), primary_key=True))

然后,我自定义了一个元组,我用它来实现if条件,如果该元组存在于类别列表中,它将被忽略,并且只有唯一的元组被提交到数据库。

这是新的视图功能:

@home.route('/edit/<int:id>', methods=['GET', 'POST'])
@login_required
def edit_post(id):
post = Post.query.get_or_404(id)
if current_user != post.author and not current_user.can(Permission.ADMINISTER):
abort(403)
form = PostForm()
form.tag.choices = [(tag.id, tag.name) for tag in Tag.query.order_by('name')]
if form.validate_on_submit():
post.body = form.body.data
# query the post-tag relationship for this post id
posttags = db.session.query(categories).filter_by(post_id=id).all()
for id in form.tag.data:
# custom tuple
if (post.id, id) not in posttags:
post.tags.append(Tag.query.get(id))
db.session.commit()
return redirect(url_for('.view_post', id=post.id))
form.body.data = post.body
form.tag.choices = [(tag.id, tag.name) for tag in Tag.query.order_by('name')]
form.tag.data = post.tags.all()
return render_template('home/edit_post.html', form=form, title='Edit Post')

最新更新