簡體   English   中英

使用數據庫中預先存在的數據編輯SelectMultipleField

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

正在構建燒瓶應用程序。 我有帖子和標簽。 發布帖子時,可以為該帖子選擇許多標簽(就像這里是堆棧溢出一樣)。 現在,問題出在要編輯帖子的位置。 由於預先存在的值,由於條目重復,我得到了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')

請幫助我解決此問題,或為我提供更好的邏輯建議。 考慮我是一個初學者。

經過無數次嘗試,我能夠成功實施編輯。 因此,首先我查詢了該表中的所有類別,並使用帖子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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM