Skip to content

CRUD - Update Record

Updating a record is straightforward:

  1. query the row
  2. modify attributes
  3. commit

Example

with app.app_context():
    user = User.query.filter_by(username="ravi").first()
    if user:
        user.username = "ravik"
        db.session.commit()
with app.app_context():
    user = User.query.filter_by(username="ravi").first()
    if user:
        user.username = "ravik"
        db.session.commit()

Common patterns

  • Update timestamps on every change
  • Validate before saving (especially on user-editable fields)

Handling missing rows

If a record doesn’t exist, decide your behavior:

  • return 404 for web routes
  • return 400 or 404 for APIs

Example in a route:

user = User.query.get_or_404(user_id)
user.username = new_username
db.session.commit()
user = User.query.get_or_404(user_id)
user.username = new_username
db.session.commit()

Partial updates

In APIs, you often implement PATCH semantics.

Be careful to only update provided fields and validate them.

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did