0
0
FlaskHow-ToBeginner · 3 min read

How to Update Data Using Flask-SQLAlchemy: Simple Guide

To update data using flask-sqlalchemy, first query the record you want to change, modify its attributes, then call db.session.commit() to save changes. This updates the existing row in the database with your new values.
📐

Syntax

Updating data in Flask-SQLAlchemy involves three main steps:

  • Query the record you want to update using Model.query.filter_by() or Model.query.get().
  • Change the attributes of the retrieved object to new values.
  • Call db.session.commit() to save the changes to the database.

This pattern ensures the database row is updated correctly.

python
record = Model.query.get(id)
record.attribute = new_value
db.session.commit()
💻

Example

This example shows how to update a user's email in a Flask app using Flask-SQLAlchemy.

python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

with app.app_context():
    db.create_all()
    # Add a user if none exists
    if not User.query.filter_by(username='alice').first():
        user = User(username='alice', email='alice@example.com')
        db.session.add(user)
        db.session.commit()

    # Update user's email
    user = User.query.filter_by(username='alice').first()
    user.email = 'alice.new@example.com'
    db.session.commit()

    # Verify update
    updated_user = User.query.filter_by(username='alice').first()
    print(f"Updated email: {updated_user.email}")
Output
Updated email: alice.new@example.com
⚠️

Common Pitfalls

Common mistakes when updating data with Flask-SQLAlchemy include:

  • Not calling db.session.commit() after changing attributes, so changes are not saved.
  • Trying to update without querying the object first, which causes errors.
  • Modifying attributes on a new object instead of the queried one.

Always query the existing record, update its fields, then commit.

python
wrong:
user = User(username='alice')  # This creates a new user, not update
user.email = 'new@example.com'
db.session.commit()  # This adds a new user, does not update existing

right:
user = User.query.filter_by(username='alice').first()
user.email = 'new@example.com'
db.session.commit()
📊

Quick Reference

Remember these key points when updating data with Flask-SQLAlchemy:

  • Use Model.query.get(id) or Model.query.filter_by() to find the record.
  • Change the object's attributes directly.
  • Call db.session.commit() to save changes.
  • Do not create a new object to update existing data.

Key Takeaways

Always query the existing record before updating its attributes.
Modify the object's fields directly, then call db.session.commit() to save.
Skipping commit() means changes won't be saved to the database.
Do not create a new object to update existing data; it adds a new row instead.
Use filter_by() or get() to find the record you want to update.