CRUD - Update Record
Updating a record is straightforward:
- query the row
- modify attributes
- 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 coffeeWas this page helpful?
Let us know how we did
