How to Delete Data Using Flask-SQLAlchemy: Simple Guide
To delete data using
flask-sqlalchemy, first query the record you want to remove, then call db.session.delete(record) followed by db.session.commit() to save changes. This removes the record from the database.Syntax
To delete a record in Flask-SQLAlchemy, use these steps:
record = Model.query.get(id): Find the record by its ID.db.session.delete(record): Mark the record for deletion.db.session.commit(): Apply the deletion to the database.
This sequence ensures the record is removed safely and changes are saved.
python
record = Model.query.get(id) db.session.delete(record) db.session.commit()
Example
This example shows how to delete a user from a database using Flask-SQLAlchemy. It defines a simple User model, adds a user, then deletes that user by ID.
python
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) with app.app_context(): db.create_all() # Add a user user = User(name='Alice') db.session.add(user) db.session.commit() # Delete the user user_to_delete = User.query.get(1) if user_to_delete: db.session.delete(user_to_delete) db.session.commit() # Check if user still exists remaining_user = User.query.get(1) print('User exists after delete:', remaining_user is not None)
Output
User exists after delete: False
Common Pitfalls
Common mistakes when deleting data with Flask-SQLAlchemy include:
- Trying to delete a record that does not exist (returns
None), causing errors. - Forgetting to call
db.session.commit(), so the deletion is not saved. - Deleting without querying the exact record, which can lead to unintended deletions.
Always check if the record exists before deleting and commit after deletion.
python
wrong = Model.query.get(999) # Non-existent ID if wrong: db.session.delete(wrong) db.session.commit() else: print('Record not found, cannot delete') # Correct way record = Model.query.get(1) if record: db.session.delete(record) db.session.commit()
Output
Record not found, cannot delete
Quick Reference
| Step | Code | Description |
|---|---|---|
| 1 | record = Model.query.get(id) | Find the record by ID |
| 2 | db.session.delete(record) | Mark the record for deletion |
| 3 | db.session.commit() | Save changes to the database |
Key Takeaways
Always query the record before deleting to avoid errors.
Use db.session.delete() followed by db.session.commit() to remove data.
Check if the record exists before attempting deletion.
Forgetting to commit will not save the deletion.
Deleting by ID is the safest and most common approach.