简体   繁体   English

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

[英]editing a SelectMultipleField with pre-existing data in the database

Am building a flask app. 正在构建烧瓶应用程序。 I have posts and tags. 我有帖子和标签。 When making a post, one can select many tags for the post (just like here is stack overflow). 发布帖子时,可以为该帖子选择许多标签(就像这里是堆栈溢出一样)。 The problem now comes in where the post is to be edited. 现在,问题出在要编辑帖子的位置。 Due to the pre-existing values, I get a sqlalchemy.exc.IntegrityError due to duplicate entries. 由于预先存在的值,由于条目重复,我得到了sqlalchemy.exc.IntegrityError I have tried removing the duplicate entries before committing to the database by 我尝试删除重复的条目,然后再提交到数据库

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

but it still brings the same error. 但它仍然带来相同的错误。 Here is the view function for editing the post: 这是用于编辑帖子的查看功能:

@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')

Kindly help me solve this or advise me on a better logic of doing this. 请帮助我解决此问题,或为我提供更好的逻辑建议。 Consider me a beginner. 考虑我是一个初学者。

After numerous trials, I was able to implement the editing successfully. 经过无数次尝试,我能够成功实施编辑。 So first I queried for all categories in this table filtering with the post id (returns a list of tuples) eg [(62, 1), (62, 4)]. 因此,首先我查询了该表中的所有类别,并使用帖子ID(返回元组列表)进行了过滤,例如[[62,1),(62,4)]。 The tuple is (post_id, tag_id). 元组是(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))

Then I custom made a tuple which I used to implement an if condition where if that tuple(s) exists in the list from categories, it is ignored and only the unique one is committed to the database. 然后,我定制了一个元组,该元组用于实现if条件,其中如果该元组存在于类别列表中,则将其忽略,并且仅将唯一的元组提交给数据库。

Here is the new view function: 这是新的视图功能:

@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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM