Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting row with Flask-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)

Thanks in advance!

like image 376
Tom Brunoli Avatar asked Feb 07 '11 11:02

Tom Brunoli


People also ask

How do I delete a row in a SQLAlchemy in Flask?

Make sure to commit for delete() to take effect. You will need to query the object first, and then delete.

How do I delete a record in SQLAlchemy?

The delete() SQL Expression Construct The delete() function generates a new instance of Delete which represents a DELETE statement in SQL, that will delete rows from a table.

How do I delete multiple rows in a Flask-SQLAlchemy?

Delete multiple rows in SQLAlchemyGet the books table from the Metadata object initialized while connecting to the database. Pass the delete query to the execute() function and get all the results using fetchall() function.


1 Answers

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.

Probably what you want to do is this:

    db.session.delete(page)
like image 133
Reiner Gerecke Avatar answered Oct 01 '22 13:10

Reiner Gerecke