使用Flask-SQLAlchemy删除行 [英] Deleting row with Flask-SQLAlchemy

查看:237
本文介绍了使用Flask-SQLAlchemy删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个函数来删除我的数据库中的记录与瓶和SQLAlchemy的扩展名。问题是,不是只删除一行,而是删除所有的行。有人可以告诉我我的代码有什么问题吗?

I'm trying to make a function to delete a record in my database with flask and the extension for SQLAlchemy. Problem is, instead of deleting just one row, it deletes all of them. Can someone tell me what's wrong with my code?

@app.route('/admin/delete/<int:page_id>', methods=['GET','POST'])
@requires_auth
def delete_page(page_id):
    page = Page.query.get(page_id)
    if not page:
        abort(404)
    if page.children:
        flash('You can not delete a page with child pages. Delete them, or assign them a different parent.',
              'error')
        return redirect(url_for('admin_page'))
    if request.method == 'POST':
        Page.query.get(page_id).query.delete()
        db.session.commit()
        flash('Page was deleted successfully', 'success')
        return redirect(url_for('admin_page'))
    return render_template('admin_delete.html', page_title=page.title, page_id=page_id)

推荐答案

我怀疑

I suspect that this line does not what you think.

    Page.query.get(page_id).query.delete()

您正在获取单个实例(您之前已经完成),并使用查询你实际上对所有对象发出一个新的查询,而不进行过滤,因此删除了所有对象。

You're getting a single instance (which you already did before), and by using query you actually issue a new query over all objects without filtering and therefore deleting all of them.

可能你想要做的是: / p>

Probably what you want to do is this:

    db.session.delete(page)

这篇关于使用Flask-SQLAlchemy删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆